diff --git a/owl-bot-staging/google-cloud-visionai/v1/.coveragerc b/owl-bot-staging/google-cloud-visionai/v1/.coveragerc new file mode 100644 index 000000000000..3fe38571c5ca --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/visionai/__init__.py + google/cloud/visionai/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-visionai/v1/.flake8 b/owl-bot-staging/google-cloud-visionai/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-visionai/v1/MANIFEST.in b/owl-bot-staging/google-cloud-visionai/v1/MANIFEST.in new file mode 100644 index 000000000000..d03b087831bf --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/visionai *.py +recursive-include google/cloud/visionai_v1 *.py diff --git a/owl-bot-staging/google-cloud-visionai/v1/README.rst b/owl-bot-staging/google-cloud-visionai/v1/README.rst new file mode 100644 index 000000000000..eade452c535b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Visionai API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Visionai 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/google-cloud-visionai/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-visionai/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/conf.py b/owl-bot-staging/google-cloud-visionai/v1/docs/conf.py new file mode 100644 index 000000000000..2484432dcdae --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-visionai documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-visionai" +copyright = u"2023, 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 = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-visionai-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-visionai.tex", + u"google-cloud-visionai Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-visionai", + u"Google Cloud Visionai Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-visionai", + u"google-cloud-visionai Documentation", + author, + "google-cloud-visionai", + "GAPIC library for Google Cloud Visionai 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/google-cloud-visionai/v1/docs/index.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/index.rst new file mode 100644 index 000000000000..7c68829e7945 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + visionai_v1/services + visionai_v1/types diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/app_platform.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/app_platform.rst new file mode 100644 index 000000000000..eebba8d97579 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/app_platform.rst @@ -0,0 +1,10 @@ +AppPlatform +----------------------------- + +.. automodule:: google.cloud.visionai_v1.services.app_platform + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1.services.app_platform.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/health_check_service.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/health_check_service.rst new file mode 100644 index 000000000000..1a20b45b314a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/health_check_service.rst @@ -0,0 +1,6 @@ +HealthCheckService +------------------------------------ + +.. automodule:: google.cloud.visionai_v1.services.health_check_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/live_video_analytics.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/live_video_analytics.rst new file mode 100644 index 000000000000..a986089c2f4d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/live_video_analytics.rst @@ -0,0 +1,10 @@ +LiveVideoAnalytics +------------------------------------ + +.. automodule:: google.cloud.visionai_v1.services.live_video_analytics + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1.services.live_video_analytics.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/services_.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/services_.rst new file mode 100644 index 000000000000..0636620c6a69 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/services_.rst @@ -0,0 +1,11 @@ +Services for Google Cloud Visionai v1 API +========================================= +.. toctree:: + :maxdepth: 2 + + app_platform + health_check_service + live_video_analytics + streaming_service + streams_service + warehouse diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/streaming_service.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/streaming_service.rst new file mode 100644 index 000000000000..cdb228da8627 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/streaming_service.rst @@ -0,0 +1,6 @@ +StreamingService +---------------------------------- + +.. automodule:: google.cloud.visionai_v1.services.streaming_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/streams_service.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/streams_service.rst new file mode 100644 index 000000000000..1e6f72467893 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/streams_service.rst @@ -0,0 +1,10 @@ +StreamsService +-------------------------------- + +.. automodule:: google.cloud.visionai_v1.services.streams_service + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1.services.streams_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/types_.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/types_.rst new file mode 100644 index 000000000000..e03c328f24e5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Visionai v1 API +====================================== + +.. automodule:: google.cloud.visionai_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/warehouse.rst b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/warehouse.rst new file mode 100644 index 000000000000..fffc1e9ede62 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/docs/visionai_v1/warehouse.rst @@ -0,0 +1,10 @@ +Warehouse +--------------------------- + +.. automodule:: google.cloud.visionai_v1.services.warehouse + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1.services.warehouse.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/__init__.py new file mode 100644 index 000000000000..e48a070570d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/__init__.py @@ -0,0 +1,745 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.visionai import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.visionai_v1.services.app_platform.client import AppPlatformClient +from google.cloud.visionai_v1.services.app_platform.async_client import AppPlatformAsyncClient +from google.cloud.visionai_v1.services.health_check_service.client import HealthCheckServiceClient +from google.cloud.visionai_v1.services.health_check_service.async_client import HealthCheckServiceAsyncClient +from google.cloud.visionai_v1.services.live_video_analytics.client import LiveVideoAnalyticsClient +from google.cloud.visionai_v1.services.live_video_analytics.async_client import LiveVideoAnalyticsAsyncClient +from google.cloud.visionai_v1.services.streaming_service.client import StreamingServiceClient +from google.cloud.visionai_v1.services.streaming_service.async_client import StreamingServiceAsyncClient +from google.cloud.visionai_v1.services.streams_service.client import StreamsServiceClient +from google.cloud.visionai_v1.services.streams_service.async_client import StreamsServiceAsyncClient +from google.cloud.visionai_v1.services.warehouse.client import WarehouseClient +from google.cloud.visionai_v1.services.warehouse.async_client import WarehouseAsyncClient + +from google.cloud.visionai_v1.types.annotations import AppPlatformCloudFunctionRequest +from google.cloud.visionai_v1.types.annotations import AppPlatformCloudFunctionResponse +from google.cloud.visionai_v1.types.annotations import AppPlatformEventBody +from google.cloud.visionai_v1.types.annotations import AppPlatformMetadata +from google.cloud.visionai_v1.types.annotations import ClassificationPredictionResult +from google.cloud.visionai_v1.types.annotations import ImageObjectDetectionPredictionResult +from google.cloud.visionai_v1.types.annotations import ImageSegmentationPredictionResult +from google.cloud.visionai_v1.types.annotations import NormalizedPolygon +from google.cloud.visionai_v1.types.annotations import NormalizedPolyline +from google.cloud.visionai_v1.types.annotations import NormalizedVertex +from google.cloud.visionai_v1.types.annotations import ObjectDetectionPredictionResult +from google.cloud.visionai_v1.types.annotations import OccupancyCountingPredictionResult +from google.cloud.visionai_v1.types.annotations import PersonalProtectiveEquipmentDetectionOutput +from google.cloud.visionai_v1.types.annotations import StreamAnnotation +from google.cloud.visionai_v1.types.annotations import StreamAnnotations +from google.cloud.visionai_v1.types.annotations import VideoActionRecognitionPredictionResult +from google.cloud.visionai_v1.types.annotations import VideoClassificationPredictionResult +from google.cloud.visionai_v1.types.annotations import VideoObjectTrackingPredictionResult +from google.cloud.visionai_v1.types.annotations import StreamAnnotationType +from google.cloud.visionai_v1.types.common import Cluster +from google.cloud.visionai_v1.types.common import GcsSource +from google.cloud.visionai_v1.types.common import OperationMetadata +from google.cloud.visionai_v1.types.health_service import ClusterInfo +from google.cloud.visionai_v1.types.health_service import HealthCheckRequest +from google.cloud.visionai_v1.types.health_service import HealthCheckResponse +from google.cloud.visionai_v1.types.lva import AnalysisDefinition +from google.cloud.visionai_v1.types.lva import AnalyzerDefinition +from google.cloud.visionai_v1.types.lva import AttributeValue +from google.cloud.visionai_v1.types.lva import OperatorDefinition +from google.cloud.visionai_v1.types.lva import ResourceSpecification +from google.cloud.visionai_v1.types.lva import RunStatus +from google.cloud.visionai_v1.types.lva import RunMode +from google.cloud.visionai_v1.types.lva_resources import Analysis +from google.cloud.visionai_v1.types.lva_resources import Operator +from google.cloud.visionai_v1.types.lva_resources import Process +from google.cloud.visionai_v1.types.lva_service import BatchRunProcessRequest +from google.cloud.visionai_v1.types.lva_service import BatchRunProcessResponse +from google.cloud.visionai_v1.types.lva_service import CreateAnalysisRequest +from google.cloud.visionai_v1.types.lva_service import CreateOperatorRequest +from google.cloud.visionai_v1.types.lva_service import CreateProcessRequest +from google.cloud.visionai_v1.types.lva_service import DeleteAnalysisRequest +from google.cloud.visionai_v1.types.lva_service import DeleteOperatorRequest +from google.cloud.visionai_v1.types.lva_service import DeleteProcessRequest +from google.cloud.visionai_v1.types.lva_service import GetAnalysisRequest +from google.cloud.visionai_v1.types.lva_service import GetOperatorRequest +from google.cloud.visionai_v1.types.lva_service import GetProcessRequest +from google.cloud.visionai_v1.types.lva_service import ListAnalysesRequest +from google.cloud.visionai_v1.types.lva_service import ListAnalysesResponse +from google.cloud.visionai_v1.types.lva_service import ListOperatorsRequest +from google.cloud.visionai_v1.types.lva_service import ListOperatorsResponse +from google.cloud.visionai_v1.types.lva_service import ListProcessesRequest +from google.cloud.visionai_v1.types.lva_service import ListProcessesResponse +from google.cloud.visionai_v1.types.lva_service import ListPublicOperatorsRequest +from google.cloud.visionai_v1.types.lva_service import ListPublicOperatorsResponse +from google.cloud.visionai_v1.types.lva_service import OperatorQuery +from google.cloud.visionai_v1.types.lva_service import ResolveOperatorInfoRequest +from google.cloud.visionai_v1.types.lva_service import ResolveOperatorInfoResponse +from google.cloud.visionai_v1.types.lva_service import UpdateAnalysisRequest +from google.cloud.visionai_v1.types.lva_service import UpdateOperatorRequest +from google.cloud.visionai_v1.types.lva_service import UpdateProcessRequest +from google.cloud.visionai_v1.types.lva_service import Registry +from google.cloud.visionai_v1.types.platform import AddApplicationStreamInputRequest +from google.cloud.visionai_v1.types.platform import AddApplicationStreamInputResponse +from google.cloud.visionai_v1.types.platform import AIEnabledDevicesInputConfig +from google.cloud.visionai_v1.types.platform import Application +from google.cloud.visionai_v1.types.platform import ApplicationConfigs +from google.cloud.visionai_v1.types.platform import ApplicationInstance +from google.cloud.visionai_v1.types.platform import ApplicationNodeAnnotation +from google.cloud.visionai_v1.types.platform import ApplicationStreamInput +from google.cloud.visionai_v1.types.platform import AutoscalingMetricSpec +from google.cloud.visionai_v1.types.platform import BigQueryConfig +from google.cloud.visionai_v1.types.platform import CreateApplicationInstancesRequest +from google.cloud.visionai_v1.types.platform import CreateApplicationInstancesResponse +from google.cloud.visionai_v1.types.platform import CreateApplicationRequest +from google.cloud.visionai_v1.types.platform import CreateDraftRequest +from google.cloud.visionai_v1.types.platform import CreateProcessorRequest +from google.cloud.visionai_v1.types.platform import CustomProcessorSourceInfo +from google.cloud.visionai_v1.types.platform import DedicatedResources +from google.cloud.visionai_v1.types.platform import DeleteApplicationInstancesRequest +from google.cloud.visionai_v1.types.platform import DeleteApplicationInstancesResponse +from google.cloud.visionai_v1.types.platform import DeleteApplicationRequest +from google.cloud.visionai_v1.types.platform import DeleteDraftRequest +from google.cloud.visionai_v1.types.platform import DeleteProcessorRequest +from google.cloud.visionai_v1.types.platform import DeployApplicationRequest +from google.cloud.visionai_v1.types.platform import DeployApplicationResponse +from google.cloud.visionai_v1.types.platform import Draft +from google.cloud.visionai_v1.types.platform import GcsOutputConfig +from google.cloud.visionai_v1.types.platform import GeneralObjectDetectionConfig +from google.cloud.visionai_v1.types.platform import GetApplicationRequest +from google.cloud.visionai_v1.types.platform import GetDraftRequest +from google.cloud.visionai_v1.types.platform import GetInstanceRequest +from google.cloud.visionai_v1.types.platform import GetProcessorRequest +from google.cloud.visionai_v1.types.platform import Instance +from google.cloud.visionai_v1.types.platform import ListApplicationsRequest +from google.cloud.visionai_v1.types.platform import ListApplicationsResponse +from google.cloud.visionai_v1.types.platform import ListDraftsRequest +from google.cloud.visionai_v1.types.platform import ListDraftsResponse +from google.cloud.visionai_v1.types.platform import ListInstancesRequest +from google.cloud.visionai_v1.types.platform import ListInstancesResponse +from google.cloud.visionai_v1.types.platform import ListPrebuiltProcessorsRequest +from google.cloud.visionai_v1.types.platform import ListPrebuiltProcessorsResponse +from google.cloud.visionai_v1.types.platform import ListProcessorsRequest +from google.cloud.visionai_v1.types.platform import ListProcessorsResponse +from google.cloud.visionai_v1.types.platform import MachineSpec +from google.cloud.visionai_v1.types.platform import MediaWarehouseConfig +from google.cloud.visionai_v1.types.platform import Node +from google.cloud.visionai_v1.types.platform import OccupancyCountConfig +from google.cloud.visionai_v1.types.platform import PersonalProtectiveEquipmentDetectionConfig +from google.cloud.visionai_v1.types.platform import PersonBlurConfig +from google.cloud.visionai_v1.types.platform import PersonVehicleDetectionConfig +from google.cloud.visionai_v1.types.platform import Processor +from google.cloud.visionai_v1.types.platform import ProcessorConfig +from google.cloud.visionai_v1.types.platform import ProcessorIOSpec +from google.cloud.visionai_v1.types.platform import ProductRecognizerConfig +from google.cloud.visionai_v1.types.platform import RemoveApplicationStreamInputRequest +from google.cloud.visionai_v1.types.platform import RemoveApplicationStreamInputResponse +from google.cloud.visionai_v1.types.platform import ResourceAnnotations +from google.cloud.visionai_v1.types.platform import StreamWithAnnotation +from google.cloud.visionai_v1.types.platform import TagParsingConfig +from google.cloud.visionai_v1.types.platform import TagRecognizerConfig +from google.cloud.visionai_v1.types.platform import UndeployApplicationRequest +from google.cloud.visionai_v1.types.platform import UndeployApplicationResponse +from google.cloud.visionai_v1.types.platform import UniversalInputConfig +from google.cloud.visionai_v1.types.platform import UpdateApplicationInstancesRequest +from google.cloud.visionai_v1.types.platform import UpdateApplicationInstancesResponse +from google.cloud.visionai_v1.types.platform import UpdateApplicationRequest +from google.cloud.visionai_v1.types.platform import UpdateApplicationStreamInputRequest +from google.cloud.visionai_v1.types.platform import UpdateApplicationStreamInputResponse +from google.cloud.visionai_v1.types.platform import UpdateDraftRequest +from google.cloud.visionai_v1.types.platform import UpdateProcessorRequest +from google.cloud.visionai_v1.types.platform import VertexAutoMLVideoConfig +from google.cloud.visionai_v1.types.platform import VertexAutoMLVisionConfig +from google.cloud.visionai_v1.types.platform import VertexCustomConfig +from google.cloud.visionai_v1.types.platform import VideoStreamInputConfig +from google.cloud.visionai_v1.types.platform import AcceleratorType +from google.cloud.visionai_v1.types.platform import DataType +from google.cloud.visionai_v1.types.platform import ModelType +from google.cloud.visionai_v1.types.streaming_resources import GstreamerBufferDescriptor +from google.cloud.visionai_v1.types.streaming_resources import Packet +from google.cloud.visionai_v1.types.streaming_resources import PacketHeader +from google.cloud.visionai_v1.types.streaming_resources import PacketType +from google.cloud.visionai_v1.types.streaming_resources import RawImageDescriptor +from google.cloud.visionai_v1.types.streaming_resources import SeriesMetadata +from google.cloud.visionai_v1.types.streaming_resources import ServerMetadata +from google.cloud.visionai_v1.types.streaming_service import AcquireLeaseRequest +from google.cloud.visionai_v1.types.streaming_service import CommitRequest +from google.cloud.visionai_v1.types.streaming_service import ControlledMode +from google.cloud.visionai_v1.types.streaming_service import EagerMode +from google.cloud.visionai_v1.types.streaming_service import EventUpdate +from google.cloud.visionai_v1.types.streaming_service import Lease +from google.cloud.visionai_v1.types.streaming_service import ReceiveEventsControlResponse +from google.cloud.visionai_v1.types.streaming_service import ReceiveEventsRequest +from google.cloud.visionai_v1.types.streaming_service import ReceiveEventsResponse +from google.cloud.visionai_v1.types.streaming_service import ReceivePacketsControlResponse +from google.cloud.visionai_v1.types.streaming_service import ReceivePacketsRequest +from google.cloud.visionai_v1.types.streaming_service import ReceivePacketsResponse +from google.cloud.visionai_v1.types.streaming_service import ReleaseLeaseRequest +from google.cloud.visionai_v1.types.streaming_service import ReleaseLeaseResponse +from google.cloud.visionai_v1.types.streaming_service import RenewLeaseRequest +from google.cloud.visionai_v1.types.streaming_service import RequestMetadata +from google.cloud.visionai_v1.types.streaming_service import SendPacketsRequest +from google.cloud.visionai_v1.types.streaming_service import SendPacketsResponse +from google.cloud.visionai_v1.types.streaming_service import LeaseType +from google.cloud.visionai_v1.types.streams_resources import Channel +from google.cloud.visionai_v1.types.streams_resources import Event +from google.cloud.visionai_v1.types.streams_resources import Series +from google.cloud.visionai_v1.types.streams_resources import Stream +from google.cloud.visionai_v1.types.streams_service import CreateClusterRequest +from google.cloud.visionai_v1.types.streams_service import CreateEventRequest +from google.cloud.visionai_v1.types.streams_service import CreateSeriesRequest +from google.cloud.visionai_v1.types.streams_service import CreateStreamRequest +from google.cloud.visionai_v1.types.streams_service import DeleteClusterRequest +from google.cloud.visionai_v1.types.streams_service import DeleteEventRequest +from google.cloud.visionai_v1.types.streams_service import DeleteSeriesRequest +from google.cloud.visionai_v1.types.streams_service import DeleteStreamRequest +from google.cloud.visionai_v1.types.streams_service import GenerateStreamHlsTokenRequest +from google.cloud.visionai_v1.types.streams_service import GenerateStreamHlsTokenResponse +from google.cloud.visionai_v1.types.streams_service import GetClusterRequest +from google.cloud.visionai_v1.types.streams_service import GetEventRequest +from google.cloud.visionai_v1.types.streams_service import GetSeriesRequest +from google.cloud.visionai_v1.types.streams_service import GetStreamRequest +from google.cloud.visionai_v1.types.streams_service import GetStreamThumbnailRequest +from google.cloud.visionai_v1.types.streams_service import GetStreamThumbnailResponse +from google.cloud.visionai_v1.types.streams_service import ListClustersRequest +from google.cloud.visionai_v1.types.streams_service import ListClustersResponse +from google.cloud.visionai_v1.types.streams_service import ListEventsRequest +from google.cloud.visionai_v1.types.streams_service import ListEventsResponse +from google.cloud.visionai_v1.types.streams_service import ListSeriesRequest +from google.cloud.visionai_v1.types.streams_service import ListSeriesResponse +from google.cloud.visionai_v1.types.streams_service import ListStreamsRequest +from google.cloud.visionai_v1.types.streams_service import ListStreamsResponse +from google.cloud.visionai_v1.types.streams_service import MaterializeChannelRequest +from google.cloud.visionai_v1.types.streams_service import UpdateClusterRequest +from google.cloud.visionai_v1.types.streams_service import UpdateEventRequest +from google.cloud.visionai_v1.types.streams_service import UpdateSeriesRequest +from google.cloud.visionai_v1.types.streams_service import UpdateStreamRequest +from google.cloud.visionai_v1.types.warehouse import AddCollectionItemRequest +from google.cloud.visionai_v1.types.warehouse import AddCollectionItemResponse +from google.cloud.visionai_v1.types.warehouse import AnalyzeAssetMetadata +from google.cloud.visionai_v1.types.warehouse import AnalyzeAssetRequest +from google.cloud.visionai_v1.types.warehouse import AnalyzeAssetResponse +from google.cloud.visionai_v1.types.warehouse import AnalyzeCorpusMetadata +from google.cloud.visionai_v1.types.warehouse import AnalyzeCorpusRequest +from google.cloud.visionai_v1.types.warehouse import AnalyzeCorpusResponse +from google.cloud.visionai_v1.types.warehouse import Annotation +from google.cloud.visionai_v1.types.warehouse import AnnotationCustomizedStruct +from google.cloud.visionai_v1.types.warehouse import AnnotationList +from google.cloud.visionai_v1.types.warehouse import AnnotationMatchingResult +from google.cloud.visionai_v1.types.warehouse import AnnotationValue +from google.cloud.visionai_v1.types.warehouse import Asset +from google.cloud.visionai_v1.types.warehouse import AssetSource +from google.cloud.visionai_v1.types.warehouse import BoolValue +from google.cloud.visionai_v1.types.warehouse import CircleArea +from google.cloud.visionai_v1.types.warehouse import ClipAssetRequest +from google.cloud.visionai_v1.types.warehouse import ClipAssetResponse +from google.cloud.visionai_v1.types.warehouse import Collection +from google.cloud.visionai_v1.types.warehouse import CollectionItem +from google.cloud.visionai_v1.types.warehouse import Corpus +from google.cloud.visionai_v1.types.warehouse import CreateAnnotationRequest +from google.cloud.visionai_v1.types.warehouse import CreateAssetRequest +from google.cloud.visionai_v1.types.warehouse import CreateCollectionMetadata +from google.cloud.visionai_v1.types.warehouse import CreateCollectionRequest +from google.cloud.visionai_v1.types.warehouse import CreateCorpusMetadata +from google.cloud.visionai_v1.types.warehouse import CreateCorpusRequest +from google.cloud.visionai_v1.types.warehouse import CreateDataSchemaRequest +from google.cloud.visionai_v1.types.warehouse import CreateIndexEndpointMetadata +from google.cloud.visionai_v1.types.warehouse import CreateIndexEndpointRequest +from google.cloud.visionai_v1.types.warehouse import CreateIndexMetadata +from google.cloud.visionai_v1.types.warehouse import CreateIndexRequest +from google.cloud.visionai_v1.types.warehouse import CreateSearchConfigRequest +from google.cloud.visionai_v1.types.warehouse import CreateSearchHypernymRequest +from google.cloud.visionai_v1.types.warehouse import Criteria +from google.cloud.visionai_v1.types.warehouse import DataSchema +from google.cloud.visionai_v1.types.warehouse import DataSchemaDetails +from google.cloud.visionai_v1.types.warehouse import DateTimeRange +from google.cloud.visionai_v1.types.warehouse import DateTimeRangeArray +from google.cloud.visionai_v1.types.warehouse import DeleteAnnotationRequest +from google.cloud.visionai_v1.types.warehouse import DeleteAssetMetadata +from google.cloud.visionai_v1.types.warehouse import DeleteAssetRequest +from google.cloud.visionai_v1.types.warehouse import DeleteCollectionMetadata +from google.cloud.visionai_v1.types.warehouse import DeleteCollectionRequest +from google.cloud.visionai_v1.types.warehouse import DeleteCorpusRequest +from google.cloud.visionai_v1.types.warehouse import DeleteDataSchemaRequest +from google.cloud.visionai_v1.types.warehouse import DeleteIndexEndpointMetadata +from google.cloud.visionai_v1.types.warehouse import DeleteIndexEndpointRequest +from google.cloud.visionai_v1.types.warehouse import DeleteIndexMetadata +from google.cloud.visionai_v1.types.warehouse import DeleteIndexRequest +from google.cloud.visionai_v1.types.warehouse import DeleteSearchConfigRequest +from google.cloud.visionai_v1.types.warehouse import DeleteSearchHypernymRequest +from google.cloud.visionai_v1.types.warehouse import DeployedIndex +from google.cloud.visionai_v1.types.warehouse import DeployedIndexReference +from google.cloud.visionai_v1.types.warehouse import DeployIndexMetadata +from google.cloud.visionai_v1.types.warehouse import DeployIndexRequest +from google.cloud.visionai_v1.types.warehouse import DeployIndexResponse +from google.cloud.visionai_v1.types.warehouse import FacetBucket +from google.cloud.visionai_v1.types.warehouse import FacetGroup +from google.cloud.visionai_v1.types.warehouse import FacetProperty +from google.cloud.visionai_v1.types.warehouse import FacetValue +from google.cloud.visionai_v1.types.warehouse import FloatRange +from google.cloud.visionai_v1.types.warehouse import FloatRangeArray +from google.cloud.visionai_v1.types.warehouse import GenerateHlsUriRequest +from google.cloud.visionai_v1.types.warehouse import GenerateHlsUriResponse +from google.cloud.visionai_v1.types.warehouse import GenerateRetrievalUrlRequest +from google.cloud.visionai_v1.types.warehouse import GenerateRetrievalUrlResponse +from google.cloud.visionai_v1.types.warehouse import GeoCoordinate +from google.cloud.visionai_v1.types.warehouse import GeoLocationArray +from google.cloud.visionai_v1.types.warehouse import GetAnnotationRequest +from google.cloud.visionai_v1.types.warehouse import GetAssetRequest +from google.cloud.visionai_v1.types.warehouse import GetCollectionRequest +from google.cloud.visionai_v1.types.warehouse import GetCorpusRequest +from google.cloud.visionai_v1.types.warehouse import GetDataSchemaRequest +from google.cloud.visionai_v1.types.warehouse import GetIndexEndpointRequest +from google.cloud.visionai_v1.types.warehouse import GetIndexRequest +from google.cloud.visionai_v1.types.warehouse import GetSearchConfigRequest +from google.cloud.visionai_v1.types.warehouse import GetSearchHypernymRequest +from google.cloud.visionai_v1.types.warehouse import ImageQuery +from google.cloud.visionai_v1.types.warehouse import ImportAssetsMetadata +from google.cloud.visionai_v1.types.warehouse import ImportAssetsRequest +from google.cloud.visionai_v1.types.warehouse import ImportAssetsResponse +from google.cloud.visionai_v1.types.warehouse import Index +from google.cloud.visionai_v1.types.warehouse import IndexAssetMetadata +from google.cloud.visionai_v1.types.warehouse import IndexAssetRequest +from google.cloud.visionai_v1.types.warehouse import IndexAssetResponse +from google.cloud.visionai_v1.types.warehouse import IndexedAsset +from google.cloud.visionai_v1.types.warehouse import IndexEndpoint +from google.cloud.visionai_v1.types.warehouse import IndexingStatus +from google.cloud.visionai_v1.types.warehouse import IngestAssetRequest +from google.cloud.visionai_v1.types.warehouse import IngestAssetResponse +from google.cloud.visionai_v1.types.warehouse import IntRange +from google.cloud.visionai_v1.types.warehouse import IntRangeArray +from google.cloud.visionai_v1.types.warehouse import ListAnnotationsRequest +from google.cloud.visionai_v1.types.warehouse import ListAnnotationsResponse +from google.cloud.visionai_v1.types.warehouse import ListAssetsRequest +from google.cloud.visionai_v1.types.warehouse import ListAssetsResponse +from google.cloud.visionai_v1.types.warehouse import ListCollectionsRequest +from google.cloud.visionai_v1.types.warehouse import ListCollectionsResponse +from google.cloud.visionai_v1.types.warehouse import ListCorporaRequest +from google.cloud.visionai_v1.types.warehouse import ListCorporaResponse +from google.cloud.visionai_v1.types.warehouse import ListDataSchemasRequest +from google.cloud.visionai_v1.types.warehouse import ListDataSchemasResponse +from google.cloud.visionai_v1.types.warehouse import ListIndexEndpointsRequest +from google.cloud.visionai_v1.types.warehouse import ListIndexEndpointsResponse +from google.cloud.visionai_v1.types.warehouse import ListIndexesRequest +from google.cloud.visionai_v1.types.warehouse import ListIndexesResponse +from google.cloud.visionai_v1.types.warehouse import ListSearchConfigsRequest +from google.cloud.visionai_v1.types.warehouse import ListSearchConfigsResponse +from google.cloud.visionai_v1.types.warehouse import ListSearchHypernymsRequest +from google.cloud.visionai_v1.types.warehouse import ListSearchHypernymsResponse +from google.cloud.visionai_v1.types.warehouse import Partition +from google.cloud.visionai_v1.types.warehouse import RemoveCollectionItemRequest +from google.cloud.visionai_v1.types.warehouse import RemoveCollectionItemResponse +from google.cloud.visionai_v1.types.warehouse import RemoveIndexAssetMetadata +from google.cloud.visionai_v1.types.warehouse import RemoveIndexAssetRequest +from google.cloud.visionai_v1.types.warehouse import RemoveIndexAssetResponse +from google.cloud.visionai_v1.types.warehouse import SchemaKeySortingStrategy +from google.cloud.visionai_v1.types.warehouse import SearchAssetsRequest +from google.cloud.visionai_v1.types.warehouse import SearchAssetsResponse +from google.cloud.visionai_v1.types.warehouse import SearchCapability +from google.cloud.visionai_v1.types.warehouse import SearchCapabilitySetting +from google.cloud.visionai_v1.types.warehouse import SearchConfig +from google.cloud.visionai_v1.types.warehouse import SearchCriteriaProperty +from google.cloud.visionai_v1.types.warehouse import SearchHypernym +from google.cloud.visionai_v1.types.warehouse import SearchIndexEndpointRequest +from google.cloud.visionai_v1.types.warehouse import SearchIndexEndpointResponse +from google.cloud.visionai_v1.types.warehouse import SearchResultItem +from google.cloud.visionai_v1.types.warehouse import StringArray +from google.cloud.visionai_v1.types.warehouse import UndeployIndexMetadata +from google.cloud.visionai_v1.types.warehouse import UndeployIndexRequest +from google.cloud.visionai_v1.types.warehouse import UndeployIndexResponse +from google.cloud.visionai_v1.types.warehouse import UpdateAnnotationRequest +from google.cloud.visionai_v1.types.warehouse import UpdateAssetRequest +from google.cloud.visionai_v1.types.warehouse import UpdateCollectionRequest +from google.cloud.visionai_v1.types.warehouse import UpdateCorpusRequest +from google.cloud.visionai_v1.types.warehouse import UpdateDataSchemaRequest +from google.cloud.visionai_v1.types.warehouse import UpdateIndexEndpointMetadata +from google.cloud.visionai_v1.types.warehouse import UpdateIndexEndpointRequest +from google.cloud.visionai_v1.types.warehouse import UpdateIndexMetadata +from google.cloud.visionai_v1.types.warehouse import UpdateIndexRequest +from google.cloud.visionai_v1.types.warehouse import UpdateSearchConfigRequest +from google.cloud.visionai_v1.types.warehouse import UpdateSearchHypernymRequest +from google.cloud.visionai_v1.types.warehouse import UploadAssetMetadata +from google.cloud.visionai_v1.types.warehouse import UploadAssetRequest +from google.cloud.visionai_v1.types.warehouse import UploadAssetResponse +from google.cloud.visionai_v1.types.warehouse import UserSpecifiedAnnotation +from google.cloud.visionai_v1.types.warehouse import ViewCollectionItemsRequest +from google.cloud.visionai_v1.types.warehouse import ViewCollectionItemsResponse +from google.cloud.visionai_v1.types.warehouse import ViewIndexedAssetsRequest +from google.cloud.visionai_v1.types.warehouse import ViewIndexedAssetsResponse +from google.cloud.visionai_v1.types.warehouse import FacetBucketType + +__all__ = ('AppPlatformClient', + 'AppPlatformAsyncClient', + 'HealthCheckServiceClient', + 'HealthCheckServiceAsyncClient', + 'LiveVideoAnalyticsClient', + 'LiveVideoAnalyticsAsyncClient', + 'StreamingServiceClient', + 'StreamingServiceAsyncClient', + 'StreamsServiceClient', + 'StreamsServiceAsyncClient', + 'WarehouseClient', + 'WarehouseAsyncClient', + 'AppPlatformCloudFunctionRequest', + 'AppPlatformCloudFunctionResponse', + 'AppPlatformEventBody', + 'AppPlatformMetadata', + 'ClassificationPredictionResult', + 'ImageObjectDetectionPredictionResult', + 'ImageSegmentationPredictionResult', + 'NormalizedPolygon', + 'NormalizedPolyline', + 'NormalizedVertex', + 'ObjectDetectionPredictionResult', + 'OccupancyCountingPredictionResult', + 'PersonalProtectiveEquipmentDetectionOutput', + 'StreamAnnotation', + 'StreamAnnotations', + 'VideoActionRecognitionPredictionResult', + 'VideoClassificationPredictionResult', + 'VideoObjectTrackingPredictionResult', + 'StreamAnnotationType', + 'Cluster', + 'GcsSource', + 'OperationMetadata', + 'ClusterInfo', + 'HealthCheckRequest', + 'HealthCheckResponse', + 'AnalysisDefinition', + 'AnalyzerDefinition', + 'AttributeValue', + 'OperatorDefinition', + 'ResourceSpecification', + 'RunStatus', + 'RunMode', + 'Analysis', + 'Operator', + 'Process', + 'BatchRunProcessRequest', + 'BatchRunProcessResponse', + 'CreateAnalysisRequest', + 'CreateOperatorRequest', + 'CreateProcessRequest', + 'DeleteAnalysisRequest', + 'DeleteOperatorRequest', + 'DeleteProcessRequest', + 'GetAnalysisRequest', + 'GetOperatorRequest', + 'GetProcessRequest', + 'ListAnalysesRequest', + 'ListAnalysesResponse', + 'ListOperatorsRequest', + 'ListOperatorsResponse', + 'ListProcessesRequest', + 'ListProcessesResponse', + 'ListPublicOperatorsRequest', + 'ListPublicOperatorsResponse', + 'OperatorQuery', + 'ResolveOperatorInfoRequest', + 'ResolveOperatorInfoResponse', + 'UpdateAnalysisRequest', + 'UpdateOperatorRequest', + 'UpdateProcessRequest', + 'Registry', + 'AddApplicationStreamInputRequest', + 'AddApplicationStreamInputResponse', + 'AIEnabledDevicesInputConfig', + 'Application', + 'ApplicationConfigs', + 'ApplicationInstance', + 'ApplicationNodeAnnotation', + 'ApplicationStreamInput', + 'AutoscalingMetricSpec', + 'BigQueryConfig', + 'CreateApplicationInstancesRequest', + 'CreateApplicationInstancesResponse', + 'CreateApplicationRequest', + 'CreateDraftRequest', + 'CreateProcessorRequest', + 'CustomProcessorSourceInfo', + 'DedicatedResources', + 'DeleteApplicationInstancesRequest', + 'DeleteApplicationInstancesResponse', + 'DeleteApplicationRequest', + 'DeleteDraftRequest', + 'DeleteProcessorRequest', + 'DeployApplicationRequest', + 'DeployApplicationResponse', + 'Draft', + 'GcsOutputConfig', + 'GeneralObjectDetectionConfig', + 'GetApplicationRequest', + 'GetDraftRequest', + 'GetInstanceRequest', + 'GetProcessorRequest', + 'Instance', + 'ListApplicationsRequest', + 'ListApplicationsResponse', + 'ListDraftsRequest', + 'ListDraftsResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListPrebuiltProcessorsRequest', + 'ListPrebuiltProcessorsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'MachineSpec', + 'MediaWarehouseConfig', + 'Node', + 'OccupancyCountConfig', + 'PersonalProtectiveEquipmentDetectionConfig', + 'PersonBlurConfig', + 'PersonVehicleDetectionConfig', + 'Processor', + 'ProcessorConfig', + 'ProcessorIOSpec', + 'ProductRecognizerConfig', + 'RemoveApplicationStreamInputRequest', + 'RemoveApplicationStreamInputResponse', + 'ResourceAnnotations', + 'StreamWithAnnotation', + 'TagParsingConfig', + 'TagRecognizerConfig', + 'UndeployApplicationRequest', + 'UndeployApplicationResponse', + 'UniversalInputConfig', + 'UpdateApplicationInstancesRequest', + 'UpdateApplicationInstancesResponse', + 'UpdateApplicationRequest', + 'UpdateApplicationStreamInputRequest', + 'UpdateApplicationStreamInputResponse', + 'UpdateDraftRequest', + 'UpdateProcessorRequest', + 'VertexAutoMLVideoConfig', + 'VertexAutoMLVisionConfig', + 'VertexCustomConfig', + 'VideoStreamInputConfig', + 'AcceleratorType', + 'DataType', + 'ModelType', + 'GstreamerBufferDescriptor', + 'Packet', + 'PacketHeader', + 'PacketType', + 'RawImageDescriptor', + 'SeriesMetadata', + 'ServerMetadata', + 'AcquireLeaseRequest', + 'CommitRequest', + 'ControlledMode', + 'EagerMode', + 'EventUpdate', + 'Lease', + 'ReceiveEventsControlResponse', + 'ReceiveEventsRequest', + 'ReceiveEventsResponse', + 'ReceivePacketsControlResponse', + 'ReceivePacketsRequest', + 'ReceivePacketsResponse', + 'ReleaseLeaseRequest', + 'ReleaseLeaseResponse', + 'RenewLeaseRequest', + 'RequestMetadata', + 'SendPacketsRequest', + 'SendPacketsResponse', + 'LeaseType', + 'Channel', + 'Event', + 'Series', + 'Stream', + 'CreateClusterRequest', + 'CreateEventRequest', + 'CreateSeriesRequest', + 'CreateStreamRequest', + 'DeleteClusterRequest', + 'DeleteEventRequest', + 'DeleteSeriesRequest', + 'DeleteStreamRequest', + 'GenerateStreamHlsTokenRequest', + 'GenerateStreamHlsTokenResponse', + 'GetClusterRequest', + 'GetEventRequest', + 'GetSeriesRequest', + 'GetStreamRequest', + 'GetStreamThumbnailRequest', + 'GetStreamThumbnailResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListEventsRequest', + 'ListEventsResponse', + 'ListSeriesRequest', + 'ListSeriesResponse', + 'ListStreamsRequest', + 'ListStreamsResponse', + 'MaterializeChannelRequest', + 'UpdateClusterRequest', + 'UpdateEventRequest', + 'UpdateSeriesRequest', + 'UpdateStreamRequest', + 'AddCollectionItemRequest', + 'AddCollectionItemResponse', + 'AnalyzeAssetMetadata', + 'AnalyzeAssetRequest', + 'AnalyzeAssetResponse', + 'AnalyzeCorpusMetadata', + 'AnalyzeCorpusRequest', + 'AnalyzeCorpusResponse', + 'Annotation', + 'AnnotationCustomizedStruct', + 'AnnotationList', + 'AnnotationMatchingResult', + 'AnnotationValue', + 'Asset', + 'AssetSource', + 'BoolValue', + 'CircleArea', + 'ClipAssetRequest', + 'ClipAssetResponse', + 'Collection', + 'CollectionItem', + 'Corpus', + 'CreateAnnotationRequest', + 'CreateAssetRequest', + 'CreateCollectionMetadata', + 'CreateCollectionRequest', + 'CreateCorpusMetadata', + 'CreateCorpusRequest', + 'CreateDataSchemaRequest', + 'CreateIndexEndpointMetadata', + 'CreateIndexEndpointRequest', + 'CreateIndexMetadata', + 'CreateIndexRequest', + 'CreateSearchConfigRequest', + 'CreateSearchHypernymRequest', + 'Criteria', + 'DataSchema', + 'DataSchemaDetails', + 'DateTimeRange', + 'DateTimeRangeArray', + 'DeleteAnnotationRequest', + 'DeleteAssetMetadata', + 'DeleteAssetRequest', + 'DeleteCollectionMetadata', + 'DeleteCollectionRequest', + 'DeleteCorpusRequest', + 'DeleteDataSchemaRequest', + 'DeleteIndexEndpointMetadata', + 'DeleteIndexEndpointRequest', + 'DeleteIndexMetadata', + 'DeleteIndexRequest', + 'DeleteSearchConfigRequest', + 'DeleteSearchHypernymRequest', + 'DeployedIndex', + 'DeployedIndexReference', + 'DeployIndexMetadata', + 'DeployIndexRequest', + 'DeployIndexResponse', + 'FacetBucket', + 'FacetGroup', + 'FacetProperty', + 'FacetValue', + 'FloatRange', + 'FloatRangeArray', + 'GenerateHlsUriRequest', + 'GenerateHlsUriResponse', + 'GenerateRetrievalUrlRequest', + 'GenerateRetrievalUrlResponse', + 'GeoCoordinate', + 'GeoLocationArray', + 'GetAnnotationRequest', + 'GetAssetRequest', + 'GetCollectionRequest', + 'GetCorpusRequest', + 'GetDataSchemaRequest', + 'GetIndexEndpointRequest', + 'GetIndexRequest', + 'GetSearchConfigRequest', + 'GetSearchHypernymRequest', + 'ImageQuery', + 'ImportAssetsMetadata', + 'ImportAssetsRequest', + 'ImportAssetsResponse', + 'Index', + 'IndexAssetMetadata', + 'IndexAssetRequest', + 'IndexAssetResponse', + 'IndexedAsset', + 'IndexEndpoint', + 'IndexingStatus', + 'IngestAssetRequest', + 'IngestAssetResponse', + 'IntRange', + 'IntRangeArray', + 'ListAnnotationsRequest', + 'ListAnnotationsResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListCollectionsRequest', + 'ListCollectionsResponse', + 'ListCorporaRequest', + 'ListCorporaResponse', + 'ListDataSchemasRequest', + 'ListDataSchemasResponse', + 'ListIndexEndpointsRequest', + 'ListIndexEndpointsResponse', + 'ListIndexesRequest', + 'ListIndexesResponse', + 'ListSearchConfigsRequest', + 'ListSearchConfigsResponse', + 'ListSearchHypernymsRequest', + 'ListSearchHypernymsResponse', + 'Partition', + 'RemoveCollectionItemRequest', + 'RemoveCollectionItemResponse', + 'RemoveIndexAssetMetadata', + 'RemoveIndexAssetRequest', + 'RemoveIndexAssetResponse', + 'SchemaKeySortingStrategy', + 'SearchAssetsRequest', + 'SearchAssetsResponse', + 'SearchCapability', + 'SearchCapabilitySetting', + 'SearchConfig', + 'SearchCriteriaProperty', + 'SearchHypernym', + 'SearchIndexEndpointRequest', + 'SearchIndexEndpointResponse', + 'SearchResultItem', + 'StringArray', + 'UndeployIndexMetadata', + 'UndeployIndexRequest', + 'UndeployIndexResponse', + 'UpdateAnnotationRequest', + 'UpdateAssetRequest', + 'UpdateCollectionRequest', + 'UpdateCorpusRequest', + 'UpdateDataSchemaRequest', + 'UpdateIndexEndpointMetadata', + 'UpdateIndexEndpointRequest', + 'UpdateIndexMetadata', + 'UpdateIndexRequest', + 'UpdateSearchConfigRequest', + 'UpdateSearchHypernymRequest', + 'UploadAssetMetadata', + 'UploadAssetRequest', + 'UploadAssetResponse', + 'UserSpecifiedAnnotation', + 'ViewCollectionItemsRequest', + 'ViewCollectionItemsResponse', + 'ViewIndexedAssetsRequest', + 'ViewIndexedAssetsResponse', + 'FacetBucketType', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/gapic_version.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/py.typed b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/py.typed new file mode 100644 index 000000000000..7b2e82d731c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-visionai package uses inline types. diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/__init__.py new file mode 100644 index 000000000000..f2f1d526f746 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/__init__.py @@ -0,0 +1,746 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.visionai_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.app_platform import AppPlatformClient +from .services.app_platform import AppPlatformAsyncClient +from .services.health_check_service import HealthCheckServiceClient +from .services.health_check_service import HealthCheckServiceAsyncClient +from .services.live_video_analytics import LiveVideoAnalyticsClient +from .services.live_video_analytics import LiveVideoAnalyticsAsyncClient +from .services.streaming_service import StreamingServiceClient +from .services.streaming_service import StreamingServiceAsyncClient +from .services.streams_service import StreamsServiceClient +from .services.streams_service import StreamsServiceAsyncClient +from .services.warehouse import WarehouseClient +from .services.warehouse import WarehouseAsyncClient + +from .types.annotations import AppPlatformCloudFunctionRequest +from .types.annotations import AppPlatformCloudFunctionResponse +from .types.annotations import AppPlatformEventBody +from .types.annotations import AppPlatformMetadata +from .types.annotations import ClassificationPredictionResult +from .types.annotations import ImageObjectDetectionPredictionResult +from .types.annotations import ImageSegmentationPredictionResult +from .types.annotations import NormalizedPolygon +from .types.annotations import NormalizedPolyline +from .types.annotations import NormalizedVertex +from .types.annotations import ObjectDetectionPredictionResult +from .types.annotations import OccupancyCountingPredictionResult +from .types.annotations import PersonalProtectiveEquipmentDetectionOutput +from .types.annotations import StreamAnnotation +from .types.annotations import StreamAnnotations +from .types.annotations import VideoActionRecognitionPredictionResult +from .types.annotations import VideoClassificationPredictionResult +from .types.annotations import VideoObjectTrackingPredictionResult +from .types.annotations import StreamAnnotationType +from .types.common import Cluster +from .types.common import GcsSource +from .types.common import OperationMetadata +from .types.health_service import ClusterInfo +from .types.health_service import HealthCheckRequest +from .types.health_service import HealthCheckResponse +from .types.lva import AnalysisDefinition +from .types.lva import AnalyzerDefinition +from .types.lva import AttributeValue +from .types.lva import OperatorDefinition +from .types.lva import ResourceSpecification +from .types.lva import RunStatus +from .types.lva import RunMode +from .types.lva_resources import Analysis +from .types.lva_resources import Operator +from .types.lva_resources import Process +from .types.lva_service import BatchRunProcessRequest +from .types.lva_service import BatchRunProcessResponse +from .types.lva_service import CreateAnalysisRequest +from .types.lva_service import CreateOperatorRequest +from .types.lva_service import CreateProcessRequest +from .types.lva_service import DeleteAnalysisRequest +from .types.lva_service import DeleteOperatorRequest +from .types.lva_service import DeleteProcessRequest +from .types.lva_service import GetAnalysisRequest +from .types.lva_service import GetOperatorRequest +from .types.lva_service import GetProcessRequest +from .types.lva_service import ListAnalysesRequest +from .types.lva_service import ListAnalysesResponse +from .types.lva_service import ListOperatorsRequest +from .types.lva_service import ListOperatorsResponse +from .types.lva_service import ListProcessesRequest +from .types.lva_service import ListProcessesResponse +from .types.lva_service import ListPublicOperatorsRequest +from .types.lva_service import ListPublicOperatorsResponse +from .types.lva_service import OperatorQuery +from .types.lva_service import ResolveOperatorInfoRequest +from .types.lva_service import ResolveOperatorInfoResponse +from .types.lva_service import UpdateAnalysisRequest +from .types.lva_service import UpdateOperatorRequest +from .types.lva_service import UpdateProcessRequest +from .types.lva_service import Registry +from .types.platform import AddApplicationStreamInputRequest +from .types.platform import AddApplicationStreamInputResponse +from .types.platform import AIEnabledDevicesInputConfig +from .types.platform import Application +from .types.platform import ApplicationConfigs +from .types.platform import ApplicationInstance +from .types.platform import ApplicationNodeAnnotation +from .types.platform import ApplicationStreamInput +from .types.platform import AutoscalingMetricSpec +from .types.platform import BigQueryConfig +from .types.platform import CreateApplicationInstancesRequest +from .types.platform import CreateApplicationInstancesResponse +from .types.platform import CreateApplicationRequest +from .types.platform import CreateDraftRequest +from .types.platform import CreateProcessorRequest +from .types.platform import CustomProcessorSourceInfo +from .types.platform import DedicatedResources +from .types.platform import DeleteApplicationInstancesRequest +from .types.platform import DeleteApplicationInstancesResponse +from .types.platform import DeleteApplicationRequest +from .types.platform import DeleteDraftRequest +from .types.platform import DeleteProcessorRequest +from .types.platform import DeployApplicationRequest +from .types.platform import DeployApplicationResponse +from .types.platform import Draft +from .types.platform import GcsOutputConfig +from .types.platform import GeneralObjectDetectionConfig +from .types.platform import GetApplicationRequest +from .types.platform import GetDraftRequest +from .types.platform import GetInstanceRequest +from .types.platform import GetProcessorRequest +from .types.platform import Instance +from .types.platform import ListApplicationsRequest +from .types.platform import ListApplicationsResponse +from .types.platform import ListDraftsRequest +from .types.platform import ListDraftsResponse +from .types.platform import ListInstancesRequest +from .types.platform import ListInstancesResponse +from .types.platform import ListPrebuiltProcessorsRequest +from .types.platform import ListPrebuiltProcessorsResponse +from .types.platform import ListProcessorsRequest +from .types.platform import ListProcessorsResponse +from .types.platform import MachineSpec +from .types.platform import MediaWarehouseConfig +from .types.platform import Node +from .types.platform import OccupancyCountConfig +from .types.platform import PersonalProtectiveEquipmentDetectionConfig +from .types.platform import PersonBlurConfig +from .types.platform import PersonVehicleDetectionConfig +from .types.platform import Processor +from .types.platform import ProcessorConfig +from .types.platform import ProcessorIOSpec +from .types.platform import ProductRecognizerConfig +from .types.platform import RemoveApplicationStreamInputRequest +from .types.platform import RemoveApplicationStreamInputResponse +from .types.platform import ResourceAnnotations +from .types.platform import StreamWithAnnotation +from .types.platform import TagParsingConfig +from .types.platform import TagRecognizerConfig +from .types.platform import UndeployApplicationRequest +from .types.platform import UndeployApplicationResponse +from .types.platform import UniversalInputConfig +from .types.platform import UpdateApplicationInstancesRequest +from .types.platform import UpdateApplicationInstancesResponse +from .types.platform import UpdateApplicationRequest +from .types.platform import UpdateApplicationStreamInputRequest +from .types.platform import UpdateApplicationStreamInputResponse +from .types.platform import UpdateDraftRequest +from .types.platform import UpdateProcessorRequest +from .types.platform import VertexAutoMLVideoConfig +from .types.platform import VertexAutoMLVisionConfig +from .types.platform import VertexCustomConfig +from .types.platform import VideoStreamInputConfig +from .types.platform import AcceleratorType +from .types.platform import DataType +from .types.platform import ModelType +from .types.streaming_resources import GstreamerBufferDescriptor +from .types.streaming_resources import Packet +from .types.streaming_resources import PacketHeader +from .types.streaming_resources import PacketType +from .types.streaming_resources import RawImageDescriptor +from .types.streaming_resources import SeriesMetadata +from .types.streaming_resources import ServerMetadata +from .types.streaming_service import AcquireLeaseRequest +from .types.streaming_service import CommitRequest +from .types.streaming_service import ControlledMode +from .types.streaming_service import EagerMode +from .types.streaming_service import EventUpdate +from .types.streaming_service import Lease +from .types.streaming_service import ReceiveEventsControlResponse +from .types.streaming_service import ReceiveEventsRequest +from .types.streaming_service import ReceiveEventsResponse +from .types.streaming_service import ReceivePacketsControlResponse +from .types.streaming_service import ReceivePacketsRequest +from .types.streaming_service import ReceivePacketsResponse +from .types.streaming_service import ReleaseLeaseRequest +from .types.streaming_service import ReleaseLeaseResponse +from .types.streaming_service import RenewLeaseRequest +from .types.streaming_service import RequestMetadata +from .types.streaming_service import SendPacketsRequest +from .types.streaming_service import SendPacketsResponse +from .types.streaming_service import LeaseType +from .types.streams_resources import Channel +from .types.streams_resources import Event +from .types.streams_resources import Series +from .types.streams_resources import Stream +from .types.streams_service import CreateClusterRequest +from .types.streams_service import CreateEventRequest +from .types.streams_service import CreateSeriesRequest +from .types.streams_service import CreateStreamRequest +from .types.streams_service import DeleteClusterRequest +from .types.streams_service import DeleteEventRequest +from .types.streams_service import DeleteSeriesRequest +from .types.streams_service import DeleteStreamRequest +from .types.streams_service import GenerateStreamHlsTokenRequest +from .types.streams_service import GenerateStreamHlsTokenResponse +from .types.streams_service import GetClusterRequest +from .types.streams_service import GetEventRequest +from .types.streams_service import GetSeriesRequest +from .types.streams_service import GetStreamRequest +from .types.streams_service import GetStreamThumbnailRequest +from .types.streams_service import GetStreamThumbnailResponse +from .types.streams_service import ListClustersRequest +from .types.streams_service import ListClustersResponse +from .types.streams_service import ListEventsRequest +from .types.streams_service import ListEventsResponse +from .types.streams_service import ListSeriesRequest +from .types.streams_service import ListSeriesResponse +from .types.streams_service import ListStreamsRequest +from .types.streams_service import ListStreamsResponse +from .types.streams_service import MaterializeChannelRequest +from .types.streams_service import UpdateClusterRequest +from .types.streams_service import UpdateEventRequest +from .types.streams_service import UpdateSeriesRequest +from .types.streams_service import UpdateStreamRequest +from .types.warehouse import AddCollectionItemRequest +from .types.warehouse import AddCollectionItemResponse +from .types.warehouse import AnalyzeAssetMetadata +from .types.warehouse import AnalyzeAssetRequest +from .types.warehouse import AnalyzeAssetResponse +from .types.warehouse import AnalyzeCorpusMetadata +from .types.warehouse import AnalyzeCorpusRequest +from .types.warehouse import AnalyzeCorpusResponse +from .types.warehouse import Annotation +from .types.warehouse import AnnotationCustomizedStruct +from .types.warehouse import AnnotationList +from .types.warehouse import AnnotationMatchingResult +from .types.warehouse import AnnotationValue +from .types.warehouse import Asset +from .types.warehouse import AssetSource +from .types.warehouse import BoolValue +from .types.warehouse import CircleArea +from .types.warehouse import ClipAssetRequest +from .types.warehouse import ClipAssetResponse +from .types.warehouse import Collection +from .types.warehouse import CollectionItem +from .types.warehouse import Corpus +from .types.warehouse import CreateAnnotationRequest +from .types.warehouse import CreateAssetRequest +from .types.warehouse import CreateCollectionMetadata +from .types.warehouse import CreateCollectionRequest +from .types.warehouse import CreateCorpusMetadata +from .types.warehouse import CreateCorpusRequest +from .types.warehouse import CreateDataSchemaRequest +from .types.warehouse import CreateIndexEndpointMetadata +from .types.warehouse import CreateIndexEndpointRequest +from .types.warehouse import CreateIndexMetadata +from .types.warehouse import CreateIndexRequest +from .types.warehouse import CreateSearchConfigRequest +from .types.warehouse import CreateSearchHypernymRequest +from .types.warehouse import Criteria +from .types.warehouse import DataSchema +from .types.warehouse import DataSchemaDetails +from .types.warehouse import DateTimeRange +from .types.warehouse import DateTimeRangeArray +from .types.warehouse import DeleteAnnotationRequest +from .types.warehouse import DeleteAssetMetadata +from .types.warehouse import DeleteAssetRequest +from .types.warehouse import DeleteCollectionMetadata +from .types.warehouse import DeleteCollectionRequest +from .types.warehouse import DeleteCorpusRequest +from .types.warehouse import DeleteDataSchemaRequest +from .types.warehouse import DeleteIndexEndpointMetadata +from .types.warehouse import DeleteIndexEndpointRequest +from .types.warehouse import DeleteIndexMetadata +from .types.warehouse import DeleteIndexRequest +from .types.warehouse import DeleteSearchConfigRequest +from .types.warehouse import DeleteSearchHypernymRequest +from .types.warehouse import DeployedIndex +from .types.warehouse import DeployedIndexReference +from .types.warehouse import DeployIndexMetadata +from .types.warehouse import DeployIndexRequest +from .types.warehouse import DeployIndexResponse +from .types.warehouse import FacetBucket +from .types.warehouse import FacetGroup +from .types.warehouse import FacetProperty +from .types.warehouse import FacetValue +from .types.warehouse import FloatRange +from .types.warehouse import FloatRangeArray +from .types.warehouse import GenerateHlsUriRequest +from .types.warehouse import GenerateHlsUriResponse +from .types.warehouse import GenerateRetrievalUrlRequest +from .types.warehouse import GenerateRetrievalUrlResponse +from .types.warehouse import GeoCoordinate +from .types.warehouse import GeoLocationArray +from .types.warehouse import GetAnnotationRequest +from .types.warehouse import GetAssetRequest +from .types.warehouse import GetCollectionRequest +from .types.warehouse import GetCorpusRequest +from .types.warehouse import GetDataSchemaRequest +from .types.warehouse import GetIndexEndpointRequest +from .types.warehouse import GetIndexRequest +from .types.warehouse import GetSearchConfigRequest +from .types.warehouse import GetSearchHypernymRequest +from .types.warehouse import ImageQuery +from .types.warehouse import ImportAssetsMetadata +from .types.warehouse import ImportAssetsRequest +from .types.warehouse import ImportAssetsResponse +from .types.warehouse import Index +from .types.warehouse import IndexAssetMetadata +from .types.warehouse import IndexAssetRequest +from .types.warehouse import IndexAssetResponse +from .types.warehouse import IndexedAsset +from .types.warehouse import IndexEndpoint +from .types.warehouse import IndexingStatus +from .types.warehouse import IngestAssetRequest +from .types.warehouse import IngestAssetResponse +from .types.warehouse import IntRange +from .types.warehouse import IntRangeArray +from .types.warehouse import ListAnnotationsRequest +from .types.warehouse import ListAnnotationsResponse +from .types.warehouse import ListAssetsRequest +from .types.warehouse import ListAssetsResponse +from .types.warehouse import ListCollectionsRequest +from .types.warehouse import ListCollectionsResponse +from .types.warehouse import ListCorporaRequest +from .types.warehouse import ListCorporaResponse +from .types.warehouse import ListDataSchemasRequest +from .types.warehouse import ListDataSchemasResponse +from .types.warehouse import ListIndexEndpointsRequest +from .types.warehouse import ListIndexEndpointsResponse +from .types.warehouse import ListIndexesRequest +from .types.warehouse import ListIndexesResponse +from .types.warehouse import ListSearchConfigsRequest +from .types.warehouse import ListSearchConfigsResponse +from .types.warehouse import ListSearchHypernymsRequest +from .types.warehouse import ListSearchHypernymsResponse +from .types.warehouse import Partition +from .types.warehouse import RemoveCollectionItemRequest +from .types.warehouse import RemoveCollectionItemResponse +from .types.warehouse import RemoveIndexAssetMetadata +from .types.warehouse import RemoveIndexAssetRequest +from .types.warehouse import RemoveIndexAssetResponse +from .types.warehouse import SchemaKeySortingStrategy +from .types.warehouse import SearchAssetsRequest +from .types.warehouse import SearchAssetsResponse +from .types.warehouse import SearchCapability +from .types.warehouse import SearchCapabilitySetting +from .types.warehouse import SearchConfig +from .types.warehouse import SearchCriteriaProperty +from .types.warehouse import SearchHypernym +from .types.warehouse import SearchIndexEndpointRequest +from .types.warehouse import SearchIndexEndpointResponse +from .types.warehouse import SearchResultItem +from .types.warehouse import StringArray +from .types.warehouse import UndeployIndexMetadata +from .types.warehouse import UndeployIndexRequest +from .types.warehouse import UndeployIndexResponse +from .types.warehouse import UpdateAnnotationRequest +from .types.warehouse import UpdateAssetRequest +from .types.warehouse import UpdateCollectionRequest +from .types.warehouse import UpdateCorpusRequest +from .types.warehouse import UpdateDataSchemaRequest +from .types.warehouse import UpdateIndexEndpointMetadata +from .types.warehouse import UpdateIndexEndpointRequest +from .types.warehouse import UpdateIndexMetadata +from .types.warehouse import UpdateIndexRequest +from .types.warehouse import UpdateSearchConfigRequest +from .types.warehouse import UpdateSearchHypernymRequest +from .types.warehouse import UploadAssetMetadata +from .types.warehouse import UploadAssetRequest +from .types.warehouse import UploadAssetResponse +from .types.warehouse import UserSpecifiedAnnotation +from .types.warehouse import ViewCollectionItemsRequest +from .types.warehouse import ViewCollectionItemsResponse +from .types.warehouse import ViewIndexedAssetsRequest +from .types.warehouse import ViewIndexedAssetsResponse +from .types.warehouse import FacetBucketType + +__all__ = ( + 'AppPlatformAsyncClient', + 'HealthCheckServiceAsyncClient', + 'LiveVideoAnalyticsAsyncClient', + 'StreamingServiceAsyncClient', + 'StreamsServiceAsyncClient', + 'WarehouseAsyncClient', +'AIEnabledDevicesInputConfig', +'AcceleratorType', +'AcquireLeaseRequest', +'AddApplicationStreamInputRequest', +'AddApplicationStreamInputResponse', +'AddCollectionItemRequest', +'AddCollectionItemResponse', +'Analysis', +'AnalysisDefinition', +'AnalyzeAssetMetadata', +'AnalyzeAssetRequest', +'AnalyzeAssetResponse', +'AnalyzeCorpusMetadata', +'AnalyzeCorpusRequest', +'AnalyzeCorpusResponse', +'AnalyzerDefinition', +'Annotation', +'AnnotationCustomizedStruct', +'AnnotationList', +'AnnotationMatchingResult', +'AnnotationValue', +'AppPlatformClient', +'AppPlatformCloudFunctionRequest', +'AppPlatformCloudFunctionResponse', +'AppPlatformEventBody', +'AppPlatformMetadata', +'Application', +'ApplicationConfigs', +'ApplicationInstance', +'ApplicationNodeAnnotation', +'ApplicationStreamInput', +'Asset', +'AssetSource', +'AttributeValue', +'AutoscalingMetricSpec', +'BatchRunProcessRequest', +'BatchRunProcessResponse', +'BigQueryConfig', +'BoolValue', +'Channel', +'CircleArea', +'ClassificationPredictionResult', +'ClipAssetRequest', +'ClipAssetResponse', +'Cluster', +'ClusterInfo', +'Collection', +'CollectionItem', +'CommitRequest', +'ControlledMode', +'Corpus', +'CreateAnalysisRequest', +'CreateAnnotationRequest', +'CreateApplicationInstancesRequest', +'CreateApplicationInstancesResponse', +'CreateApplicationRequest', +'CreateAssetRequest', +'CreateClusterRequest', +'CreateCollectionMetadata', +'CreateCollectionRequest', +'CreateCorpusMetadata', +'CreateCorpusRequest', +'CreateDataSchemaRequest', +'CreateDraftRequest', +'CreateEventRequest', +'CreateIndexEndpointMetadata', +'CreateIndexEndpointRequest', +'CreateIndexMetadata', +'CreateIndexRequest', +'CreateOperatorRequest', +'CreateProcessRequest', +'CreateProcessorRequest', +'CreateSearchConfigRequest', +'CreateSearchHypernymRequest', +'CreateSeriesRequest', +'CreateStreamRequest', +'Criteria', +'CustomProcessorSourceInfo', +'DataSchema', +'DataSchemaDetails', +'DataType', +'DateTimeRange', +'DateTimeRangeArray', +'DedicatedResources', +'DeleteAnalysisRequest', +'DeleteAnnotationRequest', +'DeleteApplicationInstancesRequest', +'DeleteApplicationInstancesResponse', +'DeleteApplicationRequest', +'DeleteAssetMetadata', +'DeleteAssetRequest', +'DeleteClusterRequest', +'DeleteCollectionMetadata', +'DeleteCollectionRequest', +'DeleteCorpusRequest', +'DeleteDataSchemaRequest', +'DeleteDraftRequest', +'DeleteEventRequest', +'DeleteIndexEndpointMetadata', +'DeleteIndexEndpointRequest', +'DeleteIndexMetadata', +'DeleteIndexRequest', +'DeleteOperatorRequest', +'DeleteProcessRequest', +'DeleteProcessorRequest', +'DeleteSearchConfigRequest', +'DeleteSearchHypernymRequest', +'DeleteSeriesRequest', +'DeleteStreamRequest', +'DeployApplicationRequest', +'DeployApplicationResponse', +'DeployIndexMetadata', +'DeployIndexRequest', +'DeployIndexResponse', +'DeployedIndex', +'DeployedIndexReference', +'Draft', +'EagerMode', +'Event', +'EventUpdate', +'FacetBucket', +'FacetBucketType', +'FacetGroup', +'FacetProperty', +'FacetValue', +'FloatRange', +'FloatRangeArray', +'GcsOutputConfig', +'GcsSource', +'GeneralObjectDetectionConfig', +'GenerateHlsUriRequest', +'GenerateHlsUriResponse', +'GenerateRetrievalUrlRequest', +'GenerateRetrievalUrlResponse', +'GenerateStreamHlsTokenRequest', +'GenerateStreamHlsTokenResponse', +'GeoCoordinate', +'GeoLocationArray', +'GetAnalysisRequest', +'GetAnnotationRequest', +'GetApplicationRequest', +'GetAssetRequest', +'GetClusterRequest', +'GetCollectionRequest', +'GetCorpusRequest', +'GetDataSchemaRequest', +'GetDraftRequest', +'GetEventRequest', +'GetIndexEndpointRequest', +'GetIndexRequest', +'GetInstanceRequest', +'GetOperatorRequest', +'GetProcessRequest', +'GetProcessorRequest', +'GetSearchConfigRequest', +'GetSearchHypernymRequest', +'GetSeriesRequest', +'GetStreamRequest', +'GetStreamThumbnailRequest', +'GetStreamThumbnailResponse', +'GstreamerBufferDescriptor', +'HealthCheckRequest', +'HealthCheckResponse', +'HealthCheckServiceClient', +'ImageObjectDetectionPredictionResult', +'ImageQuery', +'ImageSegmentationPredictionResult', +'ImportAssetsMetadata', +'ImportAssetsRequest', +'ImportAssetsResponse', +'Index', +'IndexAssetMetadata', +'IndexAssetRequest', +'IndexAssetResponse', +'IndexEndpoint', +'IndexedAsset', +'IndexingStatus', +'IngestAssetRequest', +'IngestAssetResponse', +'Instance', +'IntRange', +'IntRangeArray', +'Lease', +'LeaseType', +'ListAnalysesRequest', +'ListAnalysesResponse', +'ListAnnotationsRequest', +'ListAnnotationsResponse', +'ListApplicationsRequest', +'ListApplicationsResponse', +'ListAssetsRequest', +'ListAssetsResponse', +'ListClustersRequest', +'ListClustersResponse', +'ListCollectionsRequest', +'ListCollectionsResponse', +'ListCorporaRequest', +'ListCorporaResponse', +'ListDataSchemasRequest', +'ListDataSchemasResponse', +'ListDraftsRequest', +'ListDraftsResponse', +'ListEventsRequest', +'ListEventsResponse', +'ListIndexEndpointsRequest', +'ListIndexEndpointsResponse', +'ListIndexesRequest', +'ListIndexesResponse', +'ListInstancesRequest', +'ListInstancesResponse', +'ListOperatorsRequest', +'ListOperatorsResponse', +'ListPrebuiltProcessorsRequest', +'ListPrebuiltProcessorsResponse', +'ListProcessesRequest', +'ListProcessesResponse', +'ListProcessorsRequest', +'ListProcessorsResponse', +'ListPublicOperatorsRequest', +'ListPublicOperatorsResponse', +'ListSearchConfigsRequest', +'ListSearchConfigsResponse', +'ListSearchHypernymsRequest', +'ListSearchHypernymsResponse', +'ListSeriesRequest', +'ListSeriesResponse', +'ListStreamsRequest', +'ListStreamsResponse', +'LiveVideoAnalyticsClient', +'MachineSpec', +'MaterializeChannelRequest', +'MediaWarehouseConfig', +'ModelType', +'Node', +'NormalizedPolygon', +'NormalizedPolyline', +'NormalizedVertex', +'ObjectDetectionPredictionResult', +'OccupancyCountConfig', +'OccupancyCountingPredictionResult', +'OperationMetadata', +'Operator', +'OperatorDefinition', +'OperatorQuery', +'Packet', +'PacketHeader', +'PacketType', +'Partition', +'PersonBlurConfig', +'PersonVehicleDetectionConfig', +'PersonalProtectiveEquipmentDetectionConfig', +'PersonalProtectiveEquipmentDetectionOutput', +'Process', +'Processor', +'ProcessorConfig', +'ProcessorIOSpec', +'ProductRecognizerConfig', +'RawImageDescriptor', +'ReceiveEventsControlResponse', +'ReceiveEventsRequest', +'ReceiveEventsResponse', +'ReceivePacketsControlResponse', +'ReceivePacketsRequest', +'ReceivePacketsResponse', +'Registry', +'ReleaseLeaseRequest', +'ReleaseLeaseResponse', +'RemoveApplicationStreamInputRequest', +'RemoveApplicationStreamInputResponse', +'RemoveCollectionItemRequest', +'RemoveCollectionItemResponse', +'RemoveIndexAssetMetadata', +'RemoveIndexAssetRequest', +'RemoveIndexAssetResponse', +'RenewLeaseRequest', +'RequestMetadata', +'ResolveOperatorInfoRequest', +'ResolveOperatorInfoResponse', +'ResourceAnnotations', +'ResourceSpecification', +'RunMode', +'RunStatus', +'SchemaKeySortingStrategy', +'SearchAssetsRequest', +'SearchAssetsResponse', +'SearchCapability', +'SearchCapabilitySetting', +'SearchConfig', +'SearchCriteriaProperty', +'SearchHypernym', +'SearchIndexEndpointRequest', +'SearchIndexEndpointResponse', +'SearchResultItem', +'SendPacketsRequest', +'SendPacketsResponse', +'Series', +'SeriesMetadata', +'ServerMetadata', +'Stream', +'StreamAnnotation', +'StreamAnnotationType', +'StreamAnnotations', +'StreamWithAnnotation', +'StreamingServiceClient', +'StreamsServiceClient', +'StringArray', +'TagParsingConfig', +'TagRecognizerConfig', +'UndeployApplicationRequest', +'UndeployApplicationResponse', +'UndeployIndexMetadata', +'UndeployIndexRequest', +'UndeployIndexResponse', +'UniversalInputConfig', +'UpdateAnalysisRequest', +'UpdateAnnotationRequest', +'UpdateApplicationInstancesRequest', +'UpdateApplicationInstancesResponse', +'UpdateApplicationRequest', +'UpdateApplicationStreamInputRequest', +'UpdateApplicationStreamInputResponse', +'UpdateAssetRequest', +'UpdateClusterRequest', +'UpdateCollectionRequest', +'UpdateCorpusRequest', +'UpdateDataSchemaRequest', +'UpdateDraftRequest', +'UpdateEventRequest', +'UpdateIndexEndpointMetadata', +'UpdateIndexEndpointRequest', +'UpdateIndexMetadata', +'UpdateIndexRequest', +'UpdateOperatorRequest', +'UpdateProcessRequest', +'UpdateProcessorRequest', +'UpdateSearchConfigRequest', +'UpdateSearchHypernymRequest', +'UpdateSeriesRequest', +'UpdateStreamRequest', +'UploadAssetMetadata', +'UploadAssetRequest', +'UploadAssetResponse', +'UserSpecifiedAnnotation', +'VertexAutoMLVideoConfig', +'VertexAutoMLVisionConfig', +'VertexCustomConfig', +'VideoActionRecognitionPredictionResult', +'VideoClassificationPredictionResult', +'VideoObjectTrackingPredictionResult', +'VideoStreamInputConfig', +'ViewCollectionItemsRequest', +'ViewCollectionItemsResponse', +'ViewIndexedAssetsRequest', +'ViewIndexedAssetsResponse', +'WarehouseClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/gapic_metadata.json new file mode 100644 index 000000000000..a84d66f3a385 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/gapic_metadata.json @@ -0,0 +1,2178 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.visionai_v1", + "protoPackage": "google.cloud.visionai.v1", + "schema": "1.0", + "services": { + "AppPlatform": { + "clients": { + "grpc": { + "libraryClient": "AppPlatformClient", + "rpcs": { + "AddApplicationStreamInput": { + "methods": [ + "add_application_stream_input" + ] + }, + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "CreateApplicationInstances": { + "methods": [ + "create_application_instances" + ] + }, + "CreateDraft": { + "methods": [ + "create_draft" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteApplication": { + "methods": [ + "delete_application" + ] + }, + "DeleteApplicationInstances": { + "methods": [ + "delete_application_instances" + ] + }, + "DeleteDraft": { + "methods": [ + "delete_draft" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeployApplication": { + "methods": [ + "deploy_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "GetDraft": { + "methods": [ + "get_draft" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "ListApplications": { + "methods": [ + "list_applications" + ] + }, + "ListDrafts": { + "methods": [ + "list_drafts" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListPrebuiltProcessors": { + "methods": [ + "list_prebuilt_processors" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "RemoveApplicationStreamInput": { + "methods": [ + "remove_application_stream_input" + ] + }, + "UndeployApplication": { + "methods": [ + "undeploy_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + }, + "UpdateApplicationInstances": { + "methods": [ + "update_application_instances" + ] + }, + "UpdateApplicationStreamInput": { + "methods": [ + "update_application_stream_input" + ] + }, + "UpdateDraft": { + "methods": [ + "update_draft" + ] + }, + "UpdateProcessor": { + "methods": [ + "update_processor" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AppPlatformAsyncClient", + "rpcs": { + "AddApplicationStreamInput": { + "methods": [ + "add_application_stream_input" + ] + }, + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "CreateApplicationInstances": { + "methods": [ + "create_application_instances" + ] + }, + "CreateDraft": { + "methods": [ + "create_draft" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteApplication": { + "methods": [ + "delete_application" + ] + }, + "DeleteApplicationInstances": { + "methods": [ + "delete_application_instances" + ] + }, + "DeleteDraft": { + "methods": [ + "delete_draft" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeployApplication": { + "methods": [ + "deploy_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "GetDraft": { + "methods": [ + "get_draft" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "ListApplications": { + "methods": [ + "list_applications" + ] + }, + "ListDrafts": { + "methods": [ + "list_drafts" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListPrebuiltProcessors": { + "methods": [ + "list_prebuilt_processors" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "RemoveApplicationStreamInput": { + "methods": [ + "remove_application_stream_input" + ] + }, + "UndeployApplication": { + "methods": [ + "undeploy_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + }, + "UpdateApplicationInstances": { + "methods": [ + "update_application_instances" + ] + }, + "UpdateApplicationStreamInput": { + "methods": [ + "update_application_stream_input" + ] + }, + "UpdateDraft": { + "methods": [ + "update_draft" + ] + }, + "UpdateProcessor": { + "methods": [ + "update_processor" + ] + } + } + }, + "rest": { + "libraryClient": "AppPlatformClient", + "rpcs": { + "AddApplicationStreamInput": { + "methods": [ + "add_application_stream_input" + ] + }, + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "CreateApplicationInstances": { + "methods": [ + "create_application_instances" + ] + }, + "CreateDraft": { + "methods": [ + "create_draft" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteApplication": { + "methods": [ + "delete_application" + ] + }, + "DeleteApplicationInstances": { + "methods": [ + "delete_application_instances" + ] + }, + "DeleteDraft": { + "methods": [ + "delete_draft" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeployApplication": { + "methods": [ + "deploy_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "GetDraft": { + "methods": [ + "get_draft" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "ListApplications": { + "methods": [ + "list_applications" + ] + }, + "ListDrafts": { + "methods": [ + "list_drafts" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListPrebuiltProcessors": { + "methods": [ + "list_prebuilt_processors" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "RemoveApplicationStreamInput": { + "methods": [ + "remove_application_stream_input" + ] + }, + "UndeployApplication": { + "methods": [ + "undeploy_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + }, + "UpdateApplicationInstances": { + "methods": [ + "update_application_instances" + ] + }, + "UpdateApplicationStreamInput": { + "methods": [ + "update_application_stream_input" + ] + }, + "UpdateDraft": { + "methods": [ + "update_draft" + ] + }, + "UpdateProcessor": { + "methods": [ + "update_processor" + ] + } + } + } + } + }, + "HealthCheckService": { + "clients": { + "grpc": { + "libraryClient": "HealthCheckServiceClient", + "rpcs": { + "HealthCheck": { + "methods": [ + "health_check" + ] + } + } + }, + "grpc-async": { + "libraryClient": "HealthCheckServiceAsyncClient", + "rpcs": { + "HealthCheck": { + "methods": [ + "health_check" + ] + } + } + }, + "rest": { + "libraryClient": "HealthCheckServiceClient", + "rpcs": { + "HealthCheck": { + "methods": [ + "health_check" + ] + } + } + } + } + }, + "LiveVideoAnalytics": { + "clients": { + "grpc": { + "libraryClient": "LiveVideoAnalyticsClient", + "rpcs": { + "BatchRunProcess": { + "methods": [ + "batch_run_process" + ] + }, + "CreateAnalysis": { + "methods": [ + "create_analysis" + ] + }, + "CreateOperator": { + "methods": [ + "create_operator" + ] + }, + "CreateProcess": { + "methods": [ + "create_process" + ] + }, + "DeleteAnalysis": { + "methods": [ + "delete_analysis" + ] + }, + "DeleteOperator": { + "methods": [ + "delete_operator" + ] + }, + "DeleteProcess": { + "methods": [ + "delete_process" + ] + }, + "GetAnalysis": { + "methods": [ + "get_analysis" + ] + }, + "GetOperator": { + "methods": [ + "get_operator" + ] + }, + "GetProcess": { + "methods": [ + "get_process" + ] + }, + "ListAnalyses": { + "methods": [ + "list_analyses" + ] + }, + "ListOperators": { + "methods": [ + "list_operators" + ] + }, + "ListProcesses": { + "methods": [ + "list_processes" + ] + }, + "ListPublicOperators": { + "methods": [ + "list_public_operators" + ] + }, + "ResolveOperatorInfo": { + "methods": [ + "resolve_operator_info" + ] + }, + "UpdateAnalysis": { + "methods": [ + "update_analysis" + ] + }, + "UpdateOperator": { + "methods": [ + "update_operator" + ] + }, + "UpdateProcess": { + "methods": [ + "update_process" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LiveVideoAnalyticsAsyncClient", + "rpcs": { + "BatchRunProcess": { + "methods": [ + "batch_run_process" + ] + }, + "CreateAnalysis": { + "methods": [ + "create_analysis" + ] + }, + "CreateOperator": { + "methods": [ + "create_operator" + ] + }, + "CreateProcess": { + "methods": [ + "create_process" + ] + }, + "DeleteAnalysis": { + "methods": [ + "delete_analysis" + ] + }, + "DeleteOperator": { + "methods": [ + "delete_operator" + ] + }, + "DeleteProcess": { + "methods": [ + "delete_process" + ] + }, + "GetAnalysis": { + "methods": [ + "get_analysis" + ] + }, + "GetOperator": { + "methods": [ + "get_operator" + ] + }, + "GetProcess": { + "methods": [ + "get_process" + ] + }, + "ListAnalyses": { + "methods": [ + "list_analyses" + ] + }, + "ListOperators": { + "methods": [ + "list_operators" + ] + }, + "ListProcesses": { + "methods": [ + "list_processes" + ] + }, + "ListPublicOperators": { + "methods": [ + "list_public_operators" + ] + }, + "ResolveOperatorInfo": { + "methods": [ + "resolve_operator_info" + ] + }, + "UpdateAnalysis": { + "methods": [ + "update_analysis" + ] + }, + "UpdateOperator": { + "methods": [ + "update_operator" + ] + }, + "UpdateProcess": { + "methods": [ + "update_process" + ] + } + } + }, + "rest": { + "libraryClient": "LiveVideoAnalyticsClient", + "rpcs": { + "BatchRunProcess": { + "methods": [ + "batch_run_process" + ] + }, + "CreateAnalysis": { + "methods": [ + "create_analysis" + ] + }, + "CreateOperator": { + "methods": [ + "create_operator" + ] + }, + "CreateProcess": { + "methods": [ + "create_process" + ] + }, + "DeleteAnalysis": { + "methods": [ + "delete_analysis" + ] + }, + "DeleteOperator": { + "methods": [ + "delete_operator" + ] + }, + "DeleteProcess": { + "methods": [ + "delete_process" + ] + }, + "GetAnalysis": { + "methods": [ + "get_analysis" + ] + }, + "GetOperator": { + "methods": [ + "get_operator" + ] + }, + "GetProcess": { + "methods": [ + "get_process" + ] + }, + "ListAnalyses": { + "methods": [ + "list_analyses" + ] + }, + "ListOperators": { + "methods": [ + "list_operators" + ] + }, + "ListProcesses": { + "methods": [ + "list_processes" + ] + }, + "ListPublicOperators": { + "methods": [ + "list_public_operators" + ] + }, + "ResolveOperatorInfo": { + "methods": [ + "resolve_operator_info" + ] + }, + "UpdateAnalysis": { + "methods": [ + "update_analysis" + ] + }, + "UpdateOperator": { + "methods": [ + "update_operator" + ] + }, + "UpdateProcess": { + "methods": [ + "update_process" + ] + } + } + } + } + }, + "StreamingService": { + "clients": { + "grpc": { + "libraryClient": "StreamingServiceClient", + "rpcs": { + "AcquireLease": { + "methods": [ + "acquire_lease" + ] + }, + "ReceiveEvents": { + "methods": [ + "receive_events" + ] + }, + "ReceivePackets": { + "methods": [ + "receive_packets" + ] + }, + "ReleaseLease": { + "methods": [ + "release_lease" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "SendPackets": { + "methods": [ + "send_packets" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StreamingServiceAsyncClient", + "rpcs": { + "AcquireLease": { + "methods": [ + "acquire_lease" + ] + }, + "ReceiveEvents": { + "methods": [ + "receive_events" + ] + }, + "ReceivePackets": { + "methods": [ + "receive_packets" + ] + }, + "ReleaseLease": { + "methods": [ + "release_lease" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "SendPackets": { + "methods": [ + "send_packets" + ] + } + } + }, + "rest": { + "libraryClient": "StreamingServiceClient", + "rpcs": { + "AcquireLease": { + "methods": [ + "acquire_lease" + ] + }, + "ReceiveEvents": { + "methods": [ + "receive_events" + ] + }, + "ReceivePackets": { + "methods": [ + "receive_packets" + ] + }, + "ReleaseLease": { + "methods": [ + "release_lease" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "SendPackets": { + "methods": [ + "send_packets" + ] + } + } + } + } + }, + "StreamsService": { + "clients": { + "grpc": { + "libraryClient": "StreamsServiceClient", + "rpcs": { + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateEvent": { + "methods": [ + "create_event" + ] + }, + "CreateSeries": { + "methods": [ + "create_series" + ] + }, + "CreateStream": { + "methods": [ + "create_stream" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteEvent": { + "methods": [ + "delete_event" + ] + }, + "DeleteSeries": { + "methods": [ + "delete_series" + ] + }, + "DeleteStream": { + "methods": [ + "delete_stream" + ] + }, + "GenerateStreamHlsToken": { + "methods": [ + "generate_stream_hls_token" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetEvent": { + "methods": [ + "get_event" + ] + }, + "GetSeries": { + "methods": [ + "get_series" + ] + }, + "GetStream": { + "methods": [ + "get_stream" + ] + }, + "GetStreamThumbnail": { + "methods": [ + "get_stream_thumbnail" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListEvents": { + "methods": [ + "list_events" + ] + }, + "ListSeries": { + "methods": [ + "list_series" + ] + }, + "ListStreams": { + "methods": [ + "list_streams" + ] + }, + "MaterializeChannel": { + "methods": [ + "materialize_channel" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateEvent": { + "methods": [ + "update_event" + ] + }, + "UpdateSeries": { + "methods": [ + "update_series" + ] + }, + "UpdateStream": { + "methods": [ + "update_stream" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StreamsServiceAsyncClient", + "rpcs": { + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateEvent": { + "methods": [ + "create_event" + ] + }, + "CreateSeries": { + "methods": [ + "create_series" + ] + }, + "CreateStream": { + "methods": [ + "create_stream" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteEvent": { + "methods": [ + "delete_event" + ] + }, + "DeleteSeries": { + "methods": [ + "delete_series" + ] + }, + "DeleteStream": { + "methods": [ + "delete_stream" + ] + }, + "GenerateStreamHlsToken": { + "methods": [ + "generate_stream_hls_token" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetEvent": { + "methods": [ + "get_event" + ] + }, + "GetSeries": { + "methods": [ + "get_series" + ] + }, + "GetStream": { + "methods": [ + "get_stream" + ] + }, + "GetStreamThumbnail": { + "methods": [ + "get_stream_thumbnail" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListEvents": { + "methods": [ + "list_events" + ] + }, + "ListSeries": { + "methods": [ + "list_series" + ] + }, + "ListStreams": { + "methods": [ + "list_streams" + ] + }, + "MaterializeChannel": { + "methods": [ + "materialize_channel" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateEvent": { + "methods": [ + "update_event" + ] + }, + "UpdateSeries": { + "methods": [ + "update_series" + ] + }, + "UpdateStream": { + "methods": [ + "update_stream" + ] + } + } + }, + "rest": { + "libraryClient": "StreamsServiceClient", + "rpcs": { + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateEvent": { + "methods": [ + "create_event" + ] + }, + "CreateSeries": { + "methods": [ + "create_series" + ] + }, + "CreateStream": { + "methods": [ + "create_stream" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteEvent": { + "methods": [ + "delete_event" + ] + }, + "DeleteSeries": { + "methods": [ + "delete_series" + ] + }, + "DeleteStream": { + "methods": [ + "delete_stream" + ] + }, + "GenerateStreamHlsToken": { + "methods": [ + "generate_stream_hls_token" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetEvent": { + "methods": [ + "get_event" + ] + }, + "GetSeries": { + "methods": [ + "get_series" + ] + }, + "GetStream": { + "methods": [ + "get_stream" + ] + }, + "GetStreamThumbnail": { + "methods": [ + "get_stream_thumbnail" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListEvents": { + "methods": [ + "list_events" + ] + }, + "ListSeries": { + "methods": [ + "list_series" + ] + }, + "ListStreams": { + "methods": [ + "list_streams" + ] + }, + "MaterializeChannel": { + "methods": [ + "materialize_channel" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateEvent": { + "methods": [ + "update_event" + ] + }, + "UpdateSeries": { + "methods": [ + "update_series" + ] + }, + "UpdateStream": { + "methods": [ + "update_stream" + ] + } + } + } + } + }, + "Warehouse": { + "clients": { + "grpc": { + "libraryClient": "WarehouseClient", + "rpcs": { + "AddCollectionItem": { + "methods": [ + "add_collection_item" + ] + }, + "AnalyzeAsset": { + "methods": [ + "analyze_asset" + ] + }, + "AnalyzeCorpus": { + "methods": [ + "analyze_corpus" + ] + }, + "ClipAsset": { + "methods": [ + "clip_asset" + ] + }, + "CreateAnnotation": { + "methods": [ + "create_annotation" + ] + }, + "CreateAsset": { + "methods": [ + "create_asset" + ] + }, + "CreateCollection": { + "methods": [ + "create_collection" + ] + }, + "CreateCorpus": { + "methods": [ + "create_corpus" + ] + }, + "CreateDataSchema": { + "methods": [ + "create_data_schema" + ] + }, + "CreateIndex": { + "methods": [ + "create_index" + ] + }, + "CreateIndexEndpoint": { + "methods": [ + "create_index_endpoint" + ] + }, + "CreateSearchConfig": { + "methods": [ + "create_search_config" + ] + }, + "CreateSearchHypernym": { + "methods": [ + "create_search_hypernym" + ] + }, + "DeleteAnnotation": { + "methods": [ + "delete_annotation" + ] + }, + "DeleteAsset": { + "methods": [ + "delete_asset" + ] + }, + "DeleteCollection": { + "methods": [ + "delete_collection" + ] + }, + "DeleteCorpus": { + "methods": [ + "delete_corpus" + ] + }, + "DeleteDataSchema": { + "methods": [ + "delete_data_schema" + ] + }, + "DeleteIndex": { + "methods": [ + "delete_index" + ] + }, + "DeleteIndexEndpoint": { + "methods": [ + "delete_index_endpoint" + ] + }, + "DeleteSearchConfig": { + "methods": [ + "delete_search_config" + ] + }, + "DeleteSearchHypernym": { + "methods": [ + "delete_search_hypernym" + ] + }, + "DeployIndex": { + "methods": [ + "deploy_index" + ] + }, + "GenerateHlsUri": { + "methods": [ + "generate_hls_uri" + ] + }, + "GenerateRetrievalUrl": { + "methods": [ + "generate_retrieval_url" + ] + }, + "GetAnnotation": { + "methods": [ + "get_annotation" + ] + }, + "GetAsset": { + "methods": [ + "get_asset" + ] + }, + "GetCollection": { + "methods": [ + "get_collection" + ] + }, + "GetCorpus": { + "methods": [ + "get_corpus" + ] + }, + "GetDataSchema": { + "methods": [ + "get_data_schema" + ] + }, + "GetIndex": { + "methods": [ + "get_index" + ] + }, + "GetIndexEndpoint": { + "methods": [ + "get_index_endpoint" + ] + }, + "GetSearchConfig": { + "methods": [ + "get_search_config" + ] + }, + "GetSearchHypernym": { + "methods": [ + "get_search_hypernym" + ] + }, + "ImportAssets": { + "methods": [ + "import_assets" + ] + }, + "IndexAsset": { + "methods": [ + "index_asset" + ] + }, + "IngestAsset": { + "methods": [ + "ingest_asset" + ] + }, + "ListAnnotations": { + "methods": [ + "list_annotations" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListCollections": { + "methods": [ + "list_collections" + ] + }, + "ListCorpora": { + "methods": [ + "list_corpora" + ] + }, + "ListDataSchemas": { + "methods": [ + "list_data_schemas" + ] + }, + "ListIndexEndpoints": { + "methods": [ + "list_index_endpoints" + ] + }, + "ListIndexes": { + "methods": [ + "list_indexes" + ] + }, + "ListSearchConfigs": { + "methods": [ + "list_search_configs" + ] + }, + "ListSearchHypernyms": { + "methods": [ + "list_search_hypernyms" + ] + }, + "RemoveCollectionItem": { + "methods": [ + "remove_collection_item" + ] + }, + "RemoveIndexAsset": { + "methods": [ + "remove_index_asset" + ] + }, + "SearchAssets": { + "methods": [ + "search_assets" + ] + }, + "SearchIndexEndpoint": { + "methods": [ + "search_index_endpoint" + ] + }, + "UndeployIndex": { + "methods": [ + "undeploy_index" + ] + }, + "UpdateAnnotation": { + "methods": [ + "update_annotation" + ] + }, + "UpdateAsset": { + "methods": [ + "update_asset" + ] + }, + "UpdateCollection": { + "methods": [ + "update_collection" + ] + }, + "UpdateCorpus": { + "methods": [ + "update_corpus" + ] + }, + "UpdateDataSchema": { + "methods": [ + "update_data_schema" + ] + }, + "UpdateIndex": { + "methods": [ + "update_index" + ] + }, + "UpdateIndexEndpoint": { + "methods": [ + "update_index_endpoint" + ] + }, + "UpdateSearchConfig": { + "methods": [ + "update_search_config" + ] + }, + "UpdateSearchHypernym": { + "methods": [ + "update_search_hypernym" + ] + }, + "UploadAsset": { + "methods": [ + "upload_asset" + ] + }, + "ViewCollectionItems": { + "methods": [ + "view_collection_items" + ] + }, + "ViewIndexedAssets": { + "methods": [ + "view_indexed_assets" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WarehouseAsyncClient", + "rpcs": { + "AddCollectionItem": { + "methods": [ + "add_collection_item" + ] + }, + "AnalyzeAsset": { + "methods": [ + "analyze_asset" + ] + }, + "AnalyzeCorpus": { + "methods": [ + "analyze_corpus" + ] + }, + "ClipAsset": { + "methods": [ + "clip_asset" + ] + }, + "CreateAnnotation": { + "methods": [ + "create_annotation" + ] + }, + "CreateAsset": { + "methods": [ + "create_asset" + ] + }, + "CreateCollection": { + "methods": [ + "create_collection" + ] + }, + "CreateCorpus": { + "methods": [ + "create_corpus" + ] + }, + "CreateDataSchema": { + "methods": [ + "create_data_schema" + ] + }, + "CreateIndex": { + "methods": [ + "create_index" + ] + }, + "CreateIndexEndpoint": { + "methods": [ + "create_index_endpoint" + ] + }, + "CreateSearchConfig": { + "methods": [ + "create_search_config" + ] + }, + "CreateSearchHypernym": { + "methods": [ + "create_search_hypernym" + ] + }, + "DeleteAnnotation": { + "methods": [ + "delete_annotation" + ] + }, + "DeleteAsset": { + "methods": [ + "delete_asset" + ] + }, + "DeleteCollection": { + "methods": [ + "delete_collection" + ] + }, + "DeleteCorpus": { + "methods": [ + "delete_corpus" + ] + }, + "DeleteDataSchema": { + "methods": [ + "delete_data_schema" + ] + }, + "DeleteIndex": { + "methods": [ + "delete_index" + ] + }, + "DeleteIndexEndpoint": { + "methods": [ + "delete_index_endpoint" + ] + }, + "DeleteSearchConfig": { + "methods": [ + "delete_search_config" + ] + }, + "DeleteSearchHypernym": { + "methods": [ + "delete_search_hypernym" + ] + }, + "DeployIndex": { + "methods": [ + "deploy_index" + ] + }, + "GenerateHlsUri": { + "methods": [ + "generate_hls_uri" + ] + }, + "GenerateRetrievalUrl": { + "methods": [ + "generate_retrieval_url" + ] + }, + "GetAnnotation": { + "methods": [ + "get_annotation" + ] + }, + "GetAsset": { + "methods": [ + "get_asset" + ] + }, + "GetCollection": { + "methods": [ + "get_collection" + ] + }, + "GetCorpus": { + "methods": [ + "get_corpus" + ] + }, + "GetDataSchema": { + "methods": [ + "get_data_schema" + ] + }, + "GetIndex": { + "methods": [ + "get_index" + ] + }, + "GetIndexEndpoint": { + "methods": [ + "get_index_endpoint" + ] + }, + "GetSearchConfig": { + "methods": [ + "get_search_config" + ] + }, + "GetSearchHypernym": { + "methods": [ + "get_search_hypernym" + ] + }, + "ImportAssets": { + "methods": [ + "import_assets" + ] + }, + "IndexAsset": { + "methods": [ + "index_asset" + ] + }, + "IngestAsset": { + "methods": [ + "ingest_asset" + ] + }, + "ListAnnotations": { + "methods": [ + "list_annotations" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListCollections": { + "methods": [ + "list_collections" + ] + }, + "ListCorpora": { + "methods": [ + "list_corpora" + ] + }, + "ListDataSchemas": { + "methods": [ + "list_data_schemas" + ] + }, + "ListIndexEndpoints": { + "methods": [ + "list_index_endpoints" + ] + }, + "ListIndexes": { + "methods": [ + "list_indexes" + ] + }, + "ListSearchConfigs": { + "methods": [ + "list_search_configs" + ] + }, + "ListSearchHypernyms": { + "methods": [ + "list_search_hypernyms" + ] + }, + "RemoveCollectionItem": { + "methods": [ + "remove_collection_item" + ] + }, + "RemoveIndexAsset": { + "methods": [ + "remove_index_asset" + ] + }, + "SearchAssets": { + "methods": [ + "search_assets" + ] + }, + "SearchIndexEndpoint": { + "methods": [ + "search_index_endpoint" + ] + }, + "UndeployIndex": { + "methods": [ + "undeploy_index" + ] + }, + "UpdateAnnotation": { + "methods": [ + "update_annotation" + ] + }, + "UpdateAsset": { + "methods": [ + "update_asset" + ] + }, + "UpdateCollection": { + "methods": [ + "update_collection" + ] + }, + "UpdateCorpus": { + "methods": [ + "update_corpus" + ] + }, + "UpdateDataSchema": { + "methods": [ + "update_data_schema" + ] + }, + "UpdateIndex": { + "methods": [ + "update_index" + ] + }, + "UpdateIndexEndpoint": { + "methods": [ + "update_index_endpoint" + ] + }, + "UpdateSearchConfig": { + "methods": [ + "update_search_config" + ] + }, + "UpdateSearchHypernym": { + "methods": [ + "update_search_hypernym" + ] + }, + "UploadAsset": { + "methods": [ + "upload_asset" + ] + }, + "ViewCollectionItems": { + "methods": [ + "view_collection_items" + ] + }, + "ViewIndexedAssets": { + "methods": [ + "view_indexed_assets" + ] + } + } + }, + "rest": { + "libraryClient": "WarehouseClient", + "rpcs": { + "AddCollectionItem": { + "methods": [ + "add_collection_item" + ] + }, + "AnalyzeAsset": { + "methods": [ + "analyze_asset" + ] + }, + "AnalyzeCorpus": { + "methods": [ + "analyze_corpus" + ] + }, + "ClipAsset": { + "methods": [ + "clip_asset" + ] + }, + "CreateAnnotation": { + "methods": [ + "create_annotation" + ] + }, + "CreateAsset": { + "methods": [ + "create_asset" + ] + }, + "CreateCollection": { + "methods": [ + "create_collection" + ] + }, + "CreateCorpus": { + "methods": [ + "create_corpus" + ] + }, + "CreateDataSchema": { + "methods": [ + "create_data_schema" + ] + }, + "CreateIndex": { + "methods": [ + "create_index" + ] + }, + "CreateIndexEndpoint": { + "methods": [ + "create_index_endpoint" + ] + }, + "CreateSearchConfig": { + "methods": [ + "create_search_config" + ] + }, + "CreateSearchHypernym": { + "methods": [ + "create_search_hypernym" + ] + }, + "DeleteAnnotation": { + "methods": [ + "delete_annotation" + ] + }, + "DeleteAsset": { + "methods": [ + "delete_asset" + ] + }, + "DeleteCollection": { + "methods": [ + "delete_collection" + ] + }, + "DeleteCorpus": { + "methods": [ + "delete_corpus" + ] + }, + "DeleteDataSchema": { + "methods": [ + "delete_data_schema" + ] + }, + "DeleteIndex": { + "methods": [ + "delete_index" + ] + }, + "DeleteIndexEndpoint": { + "methods": [ + "delete_index_endpoint" + ] + }, + "DeleteSearchConfig": { + "methods": [ + "delete_search_config" + ] + }, + "DeleteSearchHypernym": { + "methods": [ + "delete_search_hypernym" + ] + }, + "DeployIndex": { + "methods": [ + "deploy_index" + ] + }, + "GenerateHlsUri": { + "methods": [ + "generate_hls_uri" + ] + }, + "GenerateRetrievalUrl": { + "methods": [ + "generate_retrieval_url" + ] + }, + "GetAnnotation": { + "methods": [ + "get_annotation" + ] + }, + "GetAsset": { + "methods": [ + "get_asset" + ] + }, + "GetCollection": { + "methods": [ + "get_collection" + ] + }, + "GetCorpus": { + "methods": [ + "get_corpus" + ] + }, + "GetDataSchema": { + "methods": [ + "get_data_schema" + ] + }, + "GetIndex": { + "methods": [ + "get_index" + ] + }, + "GetIndexEndpoint": { + "methods": [ + "get_index_endpoint" + ] + }, + "GetSearchConfig": { + "methods": [ + "get_search_config" + ] + }, + "GetSearchHypernym": { + "methods": [ + "get_search_hypernym" + ] + }, + "ImportAssets": { + "methods": [ + "import_assets" + ] + }, + "IndexAsset": { + "methods": [ + "index_asset" + ] + }, + "IngestAsset": { + "methods": [ + "ingest_asset" + ] + }, + "ListAnnotations": { + "methods": [ + "list_annotations" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListCollections": { + "methods": [ + "list_collections" + ] + }, + "ListCorpora": { + "methods": [ + "list_corpora" + ] + }, + "ListDataSchemas": { + "methods": [ + "list_data_schemas" + ] + }, + "ListIndexEndpoints": { + "methods": [ + "list_index_endpoints" + ] + }, + "ListIndexes": { + "methods": [ + "list_indexes" + ] + }, + "ListSearchConfigs": { + "methods": [ + "list_search_configs" + ] + }, + "ListSearchHypernyms": { + "methods": [ + "list_search_hypernyms" + ] + }, + "RemoveCollectionItem": { + "methods": [ + "remove_collection_item" + ] + }, + "RemoveIndexAsset": { + "methods": [ + "remove_index_asset" + ] + }, + "SearchAssets": { + "methods": [ + "search_assets" + ] + }, + "SearchIndexEndpoint": { + "methods": [ + "search_index_endpoint" + ] + }, + "UndeployIndex": { + "methods": [ + "undeploy_index" + ] + }, + "UpdateAnnotation": { + "methods": [ + "update_annotation" + ] + }, + "UpdateAsset": { + "methods": [ + "update_asset" + ] + }, + "UpdateCollection": { + "methods": [ + "update_collection" + ] + }, + "UpdateCorpus": { + "methods": [ + "update_corpus" + ] + }, + "UpdateDataSchema": { + "methods": [ + "update_data_schema" + ] + }, + "UpdateIndex": { + "methods": [ + "update_index" + ] + }, + "UpdateIndexEndpoint": { + "methods": [ + "update_index_endpoint" + ] + }, + "UpdateSearchConfig": { + "methods": [ + "update_search_config" + ] + }, + "UpdateSearchHypernym": { + "methods": [ + "update_search_hypernym" + ] + }, + "UploadAsset": { + "methods": [ + "upload_asset" + ] + }, + "ViewCollectionItems": { + "methods": [ + "view_collection_items" + ] + }, + "ViewIndexedAssets": { + "methods": [ + "view_indexed_assets" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/gapic_version.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/py.typed b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/py.typed new file mode 100644 index 000000000000..7b2e82d731c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-visionai package uses inline types. diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/__init__.py new file mode 100644 index 000000000000..0a8bf703dca7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 AppPlatformClient +from .async_client import AppPlatformAsyncClient + +__all__ = ( + 'AppPlatformClient', + 'AppPlatformAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/async_client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/async_client.py new file mode 100644 index 000000000000..9d567f7170ca --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/async_client.py @@ -0,0 +1,3589 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.app_platform import pagers +from google.cloud.visionai_v1.types import annotations +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AppPlatformTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AppPlatformGrpcAsyncIOTransport +from .client import AppPlatformClient + + +class AppPlatformAsyncClient: + """Service describing handlers for resources""" + + _client: AppPlatformClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AppPlatformClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AppPlatformClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AppPlatformClient._DEFAULT_UNIVERSE + + application_path = staticmethod(AppPlatformClient.application_path) + parse_application_path = staticmethod(AppPlatformClient.parse_application_path) + draft_path = staticmethod(AppPlatformClient.draft_path) + parse_draft_path = staticmethod(AppPlatformClient.parse_draft_path) + instance_path = staticmethod(AppPlatformClient.instance_path) + parse_instance_path = staticmethod(AppPlatformClient.parse_instance_path) + processor_path = staticmethod(AppPlatformClient.processor_path) + parse_processor_path = staticmethod(AppPlatformClient.parse_processor_path) + stream_path = staticmethod(AppPlatformClient.stream_path) + parse_stream_path = staticmethod(AppPlatformClient.parse_stream_path) + common_billing_account_path = staticmethod(AppPlatformClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AppPlatformClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AppPlatformClient.common_folder_path) + parse_common_folder_path = staticmethod(AppPlatformClient.parse_common_folder_path) + common_organization_path = staticmethod(AppPlatformClient.common_organization_path) + parse_common_organization_path = staticmethod(AppPlatformClient.parse_common_organization_path) + common_project_path = staticmethod(AppPlatformClient.common_project_path) + parse_common_project_path = staticmethod(AppPlatformClient.parse_common_project_path) + common_location_path = staticmethod(AppPlatformClient.common_location_path) + parse_common_location_path = staticmethod(AppPlatformClient.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: + AppPlatformAsyncClient: The constructed client. + """ + return AppPlatformClient.from_service_account_info.__func__(AppPlatformAsyncClient, 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: + AppPlatformAsyncClient: The constructed client. + """ + return AppPlatformClient.from_service_account_file.__func__(AppPlatformAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return AppPlatformClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AppPlatformTransport: + """Returns the transport used by the client instance. + + Returns: + AppPlatformTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(AppPlatformClient).get_transport_class, type(AppPlatformClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AppPlatformTransport, Callable[..., AppPlatformTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the app platform async 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 (Optional[Union[str,AppPlatformTransport,Callable[..., AppPlatformTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AppPlatformTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = AppPlatformClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_applications(self, + request: Optional[Union[platform.ListApplicationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApplicationsAsyncPager: + r"""Lists Applications in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_applications(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListApplicationsRequest, dict]]): + The request object. Message for requesting list of + Applications. + parent (:class:`str`): + Required. Parent value for + ListApplicationsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListApplicationsAsyncPager: + Message for response to listing + Applications. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListApplicationsRequest): + request = platform.ListApplicationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_applications] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListApplicationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_application(self, + request: Optional[Union[platform.GetApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Application: + r"""Gets details of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_application(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetApplicationRequest, dict]]): + The request object. Message for getting a Application. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Application: + Message describing Application object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetApplicationRequest): + request = platform.GetApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.get_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_application(self, + request: Optional[Union[platform.CreateApplicationRequest, dict]] = None, + *, + parent: Optional[str] = None, + application: Optional[platform.Application] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Application in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateApplicationRequest, dict]]): + The request object. Message for creating a Application. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application (:class:`google.cloud.visionai_v1.types.Application`): + Required. The resource being created. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, application]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationRequest): + request = platform.CreateApplicationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if application is not None: + request.application = application + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_application(self, + request: Optional[Union[platform.UpdateApplicationRequest, dict]] = None, + *, + application: Optional[platform.Application] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateApplicationRequest, dict]]): + The request object. Message for updating an Application. + application (:class:`google.cloud.visionai_v1.types.Application`): + Required. The resource being updated. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Application resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([application, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationRequest): + request = platform.UpdateApplicationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if application is not None: + request.application = application + 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._client._transport._wrapped_methods[self._client._transport.update_application] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("application.name", request.application.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_application(self, + request: Optional[Union[platform.DeleteApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteApplicationRequest, dict]]): + The request object. Message for deleting an Application. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationRequest): + request = platform.DeleteApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.delete_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def deploy_application(self, + request: Optional[Union[platform.DeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_deploy_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeployApplicationRequest, dict]]): + The request object. Message for deploying an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.DeployApplicationResponse` RPC Request Messages. + Message for DeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeployApplicationRequest): + request = platform.DeployApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.deploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.DeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def undeploy_application(self, + request: Optional[Union[platform.UndeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Undeploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_undeploy_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UndeployApplicationRequest, dict]]): + The request object. Message for undeploying an + Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UndeployApplicationResponse` + Message for UndeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UndeployApplicationRequest): + request = platform.UndeployApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.undeploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.UndeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def add_application_stream_input(self, + request: Optional[Union[platform.AddApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_add_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.AddApplicationStreamInputRequest, dict]]): + The request object. Message for adding stream input to an + Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.AddApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.AddApplicationStreamInputRequest): + request = platform.AddApplicationStreamInputRequest(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._client._transport._wrapped_methods[self._client._transport.add_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.AddApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def remove_application_stream_input(self, + request: Optional[Union[platform.RemoveApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.RemoveApplicationStreamInputRequest, dict]]): + The request object. Message for removing stream input + from an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.RemoveApplicationStreamInputResponse` + Message for RemoveApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.RemoveApplicationStreamInputRequest): + request = platform.RemoveApplicationStreamInputRequest(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._client._transport._wrapped_methods[self._client._transport.remove_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.RemoveApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_application_stream_input(self, + request: Optional[Union[platform.UpdateApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateApplicationStreamInputRequest, dict]]): + The request object. Message for updating stream input to + an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UpdateApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationStreamInputRequest): + request = platform.UpdateApplicationStreamInputRequest(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._client._transport._wrapped_methods[self._client._transport.update_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.UpdateApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_instances(self, + request: Optional[Union[platform.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstancesAsyncPager: + r"""Lists Instances in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListInstancesRequest, dict]]): + The request object. Message for requesting list of + Instances. + parent (:class:`str`): + Required. Parent value for + ListInstancesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListInstancesAsyncPager: + Message for response to listing + Instances. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListInstancesRequest): + request = platform.ListInstancesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_instance(self, + request: Optional[Union[platform.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_instance(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetInstanceRequest, dict]]): + The request object. Message for getting a Instance. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Instance: + Message describing Instance object + Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetInstanceRequest): + request = platform.GetInstanceRequest(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._client._transport._wrapped_methods[self._client._transport.get_instance] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_application_instances(self, + request: Optional[Union[platform.CreateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_application_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application_instances = visionai_v1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateApplicationInstancesRequest, dict]]): + The request object. Message for adding stream input to an + Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.CreateApplicationInstancesResponse` + Message for CreateApplicationInstance Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationInstancesRequest): + request = platform.CreateApplicationInstancesRequest(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._client._transport._wrapped_methods[self._client._transport.create_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.CreateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_application_instances(self, + request: Optional[Union[platform.DeleteApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_application_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteApplicationInstancesRequest, dict]]): + The request object. Message for removing stream input + from an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Instance` Message describing Instance object + Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationInstancesRequest): + request = platform.DeleteApplicationInstancesRequest(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._client._transport._wrapped_methods[self._client._transport.delete_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Instance, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_application_instances(self, + request: Optional[Union[platform.UpdateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + application_instances: Optional[MutableSequence[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_application_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest, dict]]): + The request object. Message for updating an + ApplicationInstance. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application_instances (:class:`MutableSequence[google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]`): + + This corresponds to the ``application_instances`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UpdateApplicationInstancesResponse` + Message for UpdateApplicationInstances Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, application_instances]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationInstancesRequest): + request = platform.UpdateApplicationInstancesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if application_instances: + request.application_instances.extend(application_instances) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.UpdateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_drafts(self, + request: Optional[Union[platform.ListDraftsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDraftsAsyncPager: + r"""Lists Drafts in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_drafts(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListDraftsRequest, dict]]): + The request object. Message for requesting list of + Drafts. + parent (:class:`str`): + Required. Parent value for + ListDraftsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListDraftsAsyncPager: + Message for response to listing + Drafts. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListDraftsRequest): + request = platform.ListDraftsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_drafts] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListDraftsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_draft(self, + request: Optional[Union[platform.GetDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Draft: + r"""Gets details of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = await client.get_draft(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetDraftRequest, dict]]): + The request object. Message for getting a Draft. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Draft: + Message describing Draft object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetDraftRequest): + request = platform.GetDraftRequest(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._client._transport._wrapped_methods[self._client._transport.get_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_draft(self, + request: Optional[Union[platform.CreateDraftRequest, dict]] = None, + *, + parent: Optional[str] = None, + draft: Optional[platform.Draft] = None, + draft_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Draft in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateDraftRequest, dict]]): + The request object. Message for creating a Draft. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft (:class:`google.cloud.visionai_v1.types.Draft`): + Required. The resource being created. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``draft_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Draft` Message + describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, draft, draft_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateDraftRequest): + request = platform.CreateDraftRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if draft is not None: + request.draft = draft + if draft_id is not None: + request.draft_id = draft_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_draft(self, + request: Optional[Union[platform.UpdateDraftRequest, dict]] = None, + *, + draft: Optional[platform.Draft] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateDraftRequest, dict]]): + The request object. Message for updating a Draft. + draft (:class:`google.cloud.visionai_v1.types.Draft`): + Required. The resource being updated. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Draft` Message + describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([draft, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateDraftRequest): + request = platform.UpdateDraftRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if draft is not None: + request.draft = draft + 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._client._transport._wrapped_methods[self._client._transport.update_draft] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("draft.name", request.draft.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_draft(self, + request: Optional[Union[platform.DeleteDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteDraftRequest, dict]]): + The request object. Message for deleting a Draft. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteDraftRequest): + request = platform.DeleteDraftRequest(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._client._transport._wrapped_methods[self._client._transport.delete_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_processors(self, + request: Optional[Union[platform.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsAsyncPager: + r"""Lists Processors in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_processors(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListProcessorsRequest, dict]]): + The request object. Message for requesting list of + Processors. + parent (:class:`str`): + Required. Parent value for + ListProcessorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListProcessorsAsyncPager: + Message for response to listing + Processors. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListProcessorsRequest): + request = platform.ListProcessorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListProcessorsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_prebuilt_processors(self, + request: Optional[Union[platform.ListPrebuiltProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.ListPrebuiltProcessorsResponse: + r"""ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListPrebuiltProcessorsRequest, dict]]): + The request object. Request Message for listing Prebuilt + Processors. + parent (:class:`str`): + Required. Parent path. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ListPrebuiltProcessorsResponse: + Response Message for listing Prebuilt + Processors. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListPrebuiltProcessorsRequest): + request = platform.ListPrebuiltProcessorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_prebuilt_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_processor(self, + request: Optional[Union[platform.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Processor: + r"""Gets details of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetProcessorRequest, dict]]): + The request object. Message for getting a Processor. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Processor: + Message describing Processor object. + Next ID: 19 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetProcessorRequest): + request = platform.GetProcessorRequest(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._client._transport._wrapped_methods[self._client._transport.get_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_processor(self, + request: Optional[Union[platform.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[platform.Processor] = None, + processor_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Processor in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateProcessorRequest, dict]]): + The request object. Message for creating a Processor. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (:class:`google.cloud.visionai_v1.types.Processor`): + Required. The resource being created. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``processor_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Processor` Message describing Processor object. + Next ID: 19 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, processor, processor_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateProcessorRequest): + request = platform.CreateProcessorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + if processor_id is not None: + request.processor_id = processor_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_processor(self, + request: Optional[Union[platform.UpdateProcessorRequest, dict]] = None, + *, + processor: Optional[platform.Processor] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateProcessorRequest, dict]]): + The request object. Message for updating a Processor. + processor (:class:`google.cloud.visionai_v1.types.Processor`): + Required. The resource being updated. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Processor resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Processor` Message describing Processor object. + Next ID: 19 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([processor, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateProcessorRequest): + request = platform.UpdateProcessorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if processor is not None: + request.processor = processor + 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._client._transport._wrapped_methods[self._client._transport.update_processor] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("processor.name", request.processor.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_processor(self, + request: Optional[Union[platform.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteProcessorRequest, dict]]): + The request object. Message for deleting a Processor. + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteProcessorRequest): + request = platform.DeleteProcessorRequest(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._client._transport._wrapped_methods[self._client._transport.delete_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "AppPlatformAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AppPlatformAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/client.py new file mode 100644 index 000000000000..714cd1925325 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/client.py @@ -0,0 +1,3959 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.app_platform import pagers +from google.cloud.visionai_v1.types import annotations +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AppPlatformTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AppPlatformGrpcTransport +from .transports.grpc_asyncio import AppPlatformGrpcAsyncIOTransport +from .transports.rest import AppPlatformRestTransport + + +class AppPlatformClientMeta(type): + """Metaclass for the AppPlatform 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[AppPlatformTransport]] + _transport_registry["grpc"] = AppPlatformGrpcTransport + _transport_registry["grpc_asyncio"] = AppPlatformGrpcAsyncIOTransport + _transport_registry["rest"] = AppPlatformRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AppPlatformTransport]: + """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 AppPlatformClient(metaclass=AppPlatformClientMeta): + """Service describing handlers for resources""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + AppPlatformClient: 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: + AppPlatformClient: 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) -> AppPlatformTransport: + """Returns the transport used by the client instance. + + Returns: + AppPlatformTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def application_path(project: str,location: str,application: str,) -> str: + """Returns a fully-qualified application string.""" + return "projects/{project}/locations/{location}/applications/{application}".format(project=project, location=location, application=application, ) + + @staticmethod + def parse_application_path(path: str) -> Dict[str,str]: + """Parses a application path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/applications/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def draft_path(project: str,location: str,application: str,draft: str,) -> str: + """Returns a fully-qualified draft string.""" + return "projects/{project}/locations/{location}/applications/{application}/drafts/{draft}".format(project=project, location=location, application=application, draft=draft, ) + + @staticmethod + def parse_draft_path(path: str) -> Dict[str,str]: + """Parses a draft path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/applications/(?P.+?)/drafts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def instance_path(project: str,location: str,application: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/applications/{application}/instances/{instance}".format(project=project, location=location, application=application, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/applications/(?P.+?)/instances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_path(project: str,location: str,processor: str,) -> str: + """Returns a fully-qualified processor string.""" + return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + + @staticmethod + def parse_processor_path(path: str) -> Dict[str,str]: + """Parses a processor path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def stream_path(project: str,location: str,cluster: str,stream: str,) -> str: + """Returns a fully-qualified stream string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + + @staticmethod + def parse_stream_path(path: str) -> Dict[str,str]: + """Parses a stream path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/streams/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AppPlatformClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AppPlatformClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AppPlatformClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AppPlatformClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AppPlatformClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AppPlatformTransport, Callable[..., AppPlatformTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the app platform 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 (Optional[Union[str,AppPlatformTransport,Callable[..., AppPlatformTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AppPlatformTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AppPlatformClient._read_environment_variables() + self._client_cert_source = AppPlatformClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AppPlatformClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AppPlatformTransport) + if transport_provided: + # transport is a AppPlatformTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AppPlatformTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AppPlatformClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AppPlatformTransport], Callable[..., AppPlatformTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AppPlatformTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_applications(self, + request: Optional[Union[platform.ListApplicationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApplicationsPager: + r"""Lists Applications in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_applications(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListApplicationsRequest, dict]): + The request object. Message for requesting list of + Applications. + parent (str): + Required. Parent value for + ListApplicationsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListApplicationsPager: + Message for response to listing + Applications. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListApplicationsRequest): + request = platform.ListApplicationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_applications] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListApplicationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_application(self, + request: Optional[Union[platform.GetApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Application: + r"""Gets details of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = client.get_application(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetApplicationRequest, dict]): + The request object. Message for getting a Application. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Application: + Message describing Application object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetApplicationRequest): + request = platform.GetApplicationRequest(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_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_application(self, + request: Optional[Union[platform.CreateApplicationRequest, dict]] = None, + *, + parent: Optional[str] = None, + application: Optional[platform.Application] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Application in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateApplicationRequest, dict]): + The request object. Message for creating a Application. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application (google.cloud.visionai_v1.types.Application): + Required. The resource being created. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, application]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationRequest): + request = platform.CreateApplicationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if application is not None: + request.application = application + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_application(self, + request: Optional[Union[platform.UpdateApplicationRequest, dict]] = None, + *, + application: Optional[platform.Application] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateApplicationRequest, dict]): + The request object. Message for updating an Application. + application (google.cloud.visionai_v1.types.Application): + Required. The resource being updated. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Application resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([application, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationRequest): + request = platform.UpdateApplicationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if application is not None: + request.application = application + 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_application] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("application.name", request.application.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_application(self, + request: Optional[Union[platform.DeleteApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteApplicationRequest, dict]): + The request object. Message for deleting an Application. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationRequest): + request = platform.DeleteApplicationRequest(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_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def deploy_application(self, + request: Optional[Union[platform.DeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_deploy_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeployApplicationRequest, dict]): + The request object. Message for deploying an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.DeployApplicationResponse` RPC Request Messages. + Message for DeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeployApplicationRequest): + request = platform.DeployApplicationRequest(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.deploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.DeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def undeploy_application(self, + request: Optional[Union[platform.UndeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Undeploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_undeploy_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UndeployApplicationRequest, dict]): + The request object. Message for undeploying an + Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UndeployApplicationResponse` + Message for UndeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UndeployApplicationRequest): + request = platform.UndeployApplicationRequest(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.undeploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.UndeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def add_application_stream_input(self, + request: Optional[Union[platform.AddApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_add_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.AddApplicationStreamInputRequest, dict]): + The request object. Message for adding stream input to an + Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.AddApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.AddApplicationStreamInputRequest): + request = platform.AddApplicationStreamInputRequest(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.add_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.AddApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def remove_application_stream_input(self, + request: Optional[Union[platform.RemoveApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.RemoveApplicationStreamInputRequest, dict]): + The request object. Message for removing stream input + from an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.RemoveApplicationStreamInputResponse` + Message for RemoveApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.RemoveApplicationStreamInputRequest): + request = platform.RemoveApplicationStreamInputRequest(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.remove_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.RemoveApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_application_stream_input(self, + request: Optional[Union[platform.UpdateApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateApplicationStreamInputRequest, dict]): + The request object. Message for updating stream input to + an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UpdateApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationStreamInputRequest): + request = platform.UpdateApplicationStreamInputRequest(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.update_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.UpdateApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_instances(self, + request: Optional[Union[platform.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstancesPager: + r"""Lists Instances in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListInstancesRequest, dict]): + The request object. Message for requesting list of + Instances. + parent (str): + Required. Parent value for + ListInstancesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListInstancesPager: + Message for response to listing + Instances. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListInstancesRequest): + request = platform.ListInstancesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListInstancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_instance(self, + request: Optional[Union[platform.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_instance(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetInstanceRequest, dict]): + The request object. Message for getting a Instance. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Instance: + Message describing Instance object + Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetInstanceRequest): + request = platform.GetInstanceRequest(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_instance] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_application_instances(self, + request: Optional[Union[platform.CreateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_application_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + application_instances = visionai_v1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateApplicationInstancesRequest, dict]): + The request object. Message for adding stream input to an + Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.CreateApplicationInstancesResponse` + Message for CreateApplicationInstance Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationInstancesRequest): + request = platform.CreateApplicationInstancesRequest(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.create_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.CreateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_application_instances(self, + request: Optional[Union[platform.DeleteApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_application_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteApplicationInstancesRequest, dict]): + The request object. Message for removing stream input + from an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Instance` Message describing Instance object + Next ID: 12 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationInstancesRequest): + request = platform.DeleteApplicationInstancesRequest(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_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Instance, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_application_instances(self, + request: Optional[Union[platform.UpdateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + application_instances: Optional[MutableSequence[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_application_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest, dict]): + The request object. Message for updating an + ApplicationInstance. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application_instances (MutableSequence[google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]): + + This corresponds to the ``application_instances`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UpdateApplicationInstancesResponse` + Message for UpdateApplicationInstances Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, application_instances]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationInstancesRequest): + request = platform.UpdateApplicationInstancesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if application_instances is not None: + request.application_instances = application_instances + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.UpdateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_drafts(self, + request: Optional[Union[platform.ListDraftsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDraftsPager: + r"""Lists Drafts in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_drafts(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListDraftsRequest, dict]): + The request object. Message for requesting list of + Drafts. + parent (str): + Required. Parent value for + ListDraftsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListDraftsPager: + Message for response to listing + Drafts. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListDraftsRequest): + request = platform.ListDraftsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_drafts] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListDraftsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_draft(self, + request: Optional[Union[platform.GetDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Draft: + r"""Gets details of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = client.get_draft(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetDraftRequest, dict]): + The request object. Message for getting a Draft. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Draft: + Message describing Draft object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetDraftRequest): + request = platform.GetDraftRequest(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_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_draft(self, + request: Optional[Union[platform.CreateDraftRequest, dict]] = None, + *, + parent: Optional[str] = None, + draft: Optional[platform.Draft] = None, + draft_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Draft in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateDraftRequest, dict]): + The request object. Message for creating a Draft. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft (google.cloud.visionai_v1.types.Draft): + Required. The resource being created. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``draft_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Draft` Message + describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, draft, draft_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateDraftRequest): + request = platform.CreateDraftRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if draft is not None: + request.draft = draft + if draft_id is not None: + request.draft_id = draft_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_draft(self, + request: Optional[Union[platform.UpdateDraftRequest, dict]] = None, + *, + draft: Optional[platform.Draft] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateDraftRequest, dict]): + The request object. Message for updating a Draft. + draft (google.cloud.visionai_v1.types.Draft): + Required. The resource being updated. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Draft` Message + describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([draft, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateDraftRequest): + request = platform.UpdateDraftRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if draft is not None: + request.draft = draft + 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_draft] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("draft.name", request.draft.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_draft(self, + request: Optional[Union[platform.DeleteDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteDraftRequest, dict]): + The request object. Message for deleting a Draft. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteDraftRequest): + request = platform.DeleteDraftRequest(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_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_processors(self, + request: Optional[Union[platform.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsPager: + r"""Lists Processors in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_processors(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListProcessorsRequest, dict]): + The request object. Message for requesting list of + Processors. + parent (str): + Required. Parent value for + ListProcessorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.app_platform.pagers.ListProcessorsPager: + Message for response to listing + Processors. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListProcessorsRequest): + request = platform.ListProcessorsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListProcessorsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_prebuilt_processors(self, + request: Optional[Union[platform.ListPrebuiltProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.ListPrebuiltProcessorsResponse: + r"""ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListPrebuiltProcessorsRequest, dict]): + The request object. Request Message for listing Prebuilt + Processors. + parent (str): + Required. Parent path. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ListPrebuiltProcessorsResponse: + Response Message for listing Prebuilt + Processors. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListPrebuiltProcessorsRequest): + request = platform.ListPrebuiltProcessorsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_prebuilt_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_processor(self, + request: Optional[Union[platform.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Processor: + r"""Gets details of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetProcessorRequest, dict]): + The request object. Message for getting a Processor. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Processor: + Message describing Processor object. + Next ID: 19 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetProcessorRequest): + request = platform.GetProcessorRequest(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_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_processor(self, + request: Optional[Union[platform.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[platform.Processor] = None, + processor_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Processor in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateProcessorRequest, dict]): + The request object. Message for creating a Processor. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (google.cloud.visionai_v1.types.Processor): + Required. The resource being created. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``processor_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Processor` Message describing Processor object. + Next ID: 19 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, processor, processor_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateProcessorRequest): + request = platform.CreateProcessorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + if processor_id is not None: + request.processor_id = processor_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_processor(self, + request: Optional[Union[platform.UpdateProcessorRequest, dict]] = None, + *, + processor: Optional[platform.Processor] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateProcessorRequest, dict]): + The request object. Message for updating a Processor. + processor (google.cloud.visionai_v1.types.Processor): + Required. The resource being updated. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Processor resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Processor` Message describing Processor object. + Next ID: 19 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([processor, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateProcessorRequest): + request = platform.UpdateProcessorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if processor is not None: + request.processor = processor + 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_processor] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("processor.name", request.processor.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_processor(self, + request: Optional[Union[platform.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteProcessorRequest, dict]): + The request object. Message for deleting a Processor. + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteProcessorRequest): + request = platform.DeleteProcessorRequest(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_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AppPlatformClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AppPlatformClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/pagers.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/pagers.py new file mode 100644 index 000000000000..8529ae054798 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/pagers.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1.types import platform + + +class ListApplicationsPager: + """A pager for iterating through ``list_applications`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListApplicationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``applications`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApplications`` requests and continue to iterate + through the ``applications`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListApplicationsResponse` + 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[..., platform.ListApplicationsResponse], + request: platform.ListApplicationsRequest, + response: platform.ListApplicationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListApplicationsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListApplicationsResponse): + 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 = platform.ListApplicationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListApplicationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Application]: + for page in self.pages: + yield from page.applications + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApplicationsAsyncPager: + """A pager for iterating through ``list_applications`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListApplicationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``applications`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApplications`` requests and continue to iterate + through the ``applications`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListApplicationsResponse` + 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[platform.ListApplicationsResponse]], + request: platform.ListApplicationsRequest, + response: platform.ListApplicationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListApplicationsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListApplicationsResponse): + 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 = platform.ListApplicationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListApplicationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Application]: + async def async_generator(): + async for page in self.pages: + for response in page.applications: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListInstancesResponse` + 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[..., platform.ListInstancesResponse], + request: platform.ListInstancesRequest, + response: platform.ListInstancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListInstancesResponse): + 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 = platform.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListInstancesResponse` + 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[platform.ListInstancesResponse]], + request: platform.ListInstancesRequest, + response: platform.ListInstancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListInstancesResponse): + 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 = platform.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDraftsPager: + """A pager for iterating through ``list_drafts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListDraftsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``drafts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDrafts`` requests and continue to iterate + through the ``drafts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListDraftsResponse` + 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[..., platform.ListDraftsResponse], + request: platform.ListDraftsRequest, + response: platform.ListDraftsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListDraftsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListDraftsResponse): + 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 = platform.ListDraftsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListDraftsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Draft]: + for page in self.pages: + yield from page.drafts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDraftsAsyncPager: + """A pager for iterating through ``list_drafts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListDraftsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``drafts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDrafts`` requests and continue to iterate + through the ``drafts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListDraftsResponse` + 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[platform.ListDraftsResponse]], + request: platform.ListDraftsRequest, + response: platform.ListDraftsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListDraftsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListDraftsResponse): + 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 = platform.ListDraftsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListDraftsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Draft]: + async def async_generator(): + async for page in self.pages: + for response in page.drafts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListProcessorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListProcessorsResponse` + 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[..., platform.ListProcessorsResponse], + request: platform.ListProcessorsRequest, + response: platform.ListProcessorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListProcessorsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListProcessorsResponse): + 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 = platform.ListProcessorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListProcessorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Processor]: + for page in self.pages: + yield from page.processors + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsAsyncPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListProcessorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListProcessorsResponse` + 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[platform.ListProcessorsResponse]], + request: platform.ListProcessorsRequest, + response: platform.ListProcessorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListProcessorsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListProcessorsResponse): + 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 = platform.ListProcessorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListProcessorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Processor]: + async def async_generator(): + async for page in self.pages: + for response in page.processors: + 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/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/__init__.py new file mode 100644 index 000000000000..cab5e0b65301 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 AppPlatformTransport +from .grpc import AppPlatformGrpcTransport +from .grpc_asyncio import AppPlatformGrpcAsyncIOTransport +from .rest import AppPlatformRestTransport +from .rest import AppPlatformRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AppPlatformTransport]] +_transport_registry['grpc'] = AppPlatformGrpcTransport +_transport_registry['grpc_asyncio'] = AppPlatformGrpcAsyncIOTransport +_transport_registry['rest'] = AppPlatformRestTransport + +__all__ = ( + 'AppPlatformTransport', + 'AppPlatformGrpcTransport', + 'AppPlatformGrpcAsyncIOTransport', + 'AppPlatformRestTransport', + 'AppPlatformRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/base.py new file mode 100644 index 000000000000..f67a1e6f0ae0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/base.py @@ -0,0 +1,548 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AppPlatformTransport(abc.ABC): + """Abstract transport class for AppPlatform.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_applications: gapic_v1.method.wrap_method( + self.list_applications, + default_timeout=None, + client_info=client_info, + ), + self.get_application: gapic_v1.method.wrap_method( + self.get_application, + default_timeout=None, + client_info=client_info, + ), + self.create_application: gapic_v1.method.wrap_method( + self.create_application, + default_timeout=None, + client_info=client_info, + ), + self.update_application: gapic_v1.method.wrap_method( + self.update_application, + default_timeout=None, + client_info=client_info, + ), + self.delete_application: gapic_v1.method.wrap_method( + self.delete_application, + default_timeout=None, + client_info=client_info, + ), + self.deploy_application: gapic_v1.method.wrap_method( + self.deploy_application, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_application: gapic_v1.method.wrap_method( + self.undeploy_application, + default_timeout=None, + client_info=client_info, + ), + self.add_application_stream_input: gapic_v1.method.wrap_method( + self.add_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.remove_application_stream_input: gapic_v1.method.wrap_method( + self.remove_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.update_application_stream_input: gapic_v1.method.wrap_method( + self.update_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_application_instances: gapic_v1.method.wrap_method( + self.create_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.delete_application_instances: gapic_v1.method.wrap_method( + self.delete_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.update_application_instances: gapic_v1.method.wrap_method( + self.update_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.list_drafts: gapic_v1.method.wrap_method( + self.list_drafts, + default_timeout=None, + client_info=client_info, + ), + self.get_draft: gapic_v1.method.wrap_method( + self.get_draft, + default_timeout=None, + client_info=client_info, + ), + self.create_draft: gapic_v1.method.wrap_method( + self.create_draft, + default_timeout=None, + client_info=client_info, + ), + self.update_draft: gapic_v1.method.wrap_method( + self.update_draft, + default_timeout=None, + client_info=client_info, + ), + self.delete_draft: gapic_v1.method.wrap_method( + self.delete_draft, + default_timeout=None, + client_info=client_info, + ), + self.list_processors: gapic_v1.method.wrap_method( + self.list_processors, + default_timeout=None, + client_info=client_info, + ), + self.list_prebuilt_processors: gapic_v1.method.wrap_method( + self.list_prebuilt_processors, + default_timeout=None, + client_info=client_info, + ), + self.get_processor: gapic_v1.method.wrap_method( + self.get_processor, + default_timeout=None, + client_info=client_info, + ), + self.create_processor: gapic_v1.method.wrap_method( + self.create_processor, + default_timeout=None, + client_info=client_info, + ), + self.update_processor: gapic_v1.method.wrap_method( + self.update_processor, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor: gapic_v1.method.wrap_method( + self.delete_processor, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + Union[ + platform.ListApplicationsResponse, + Awaitable[platform.ListApplicationsResponse] + ]]: + raise NotImplementedError() + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + Union[ + platform.Application, + Awaitable[platform.Application] + ]]: + raise NotImplementedError() + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + Union[ + platform.ListInstancesResponse, + Awaitable[platform.ListInstancesResponse] + ]]: + raise NotImplementedError() + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + Union[ + platform.Instance, + Awaitable[platform.Instance] + ]]: + raise NotImplementedError() + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + Union[ + platform.ListDraftsResponse, + Awaitable[platform.ListDraftsResponse] + ]]: + raise NotImplementedError() + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + Union[ + platform.Draft, + Awaitable[platform.Draft] + ]]: + raise NotImplementedError() + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + Union[ + platform.ListProcessorsResponse, + Awaitable[platform.ListProcessorsResponse] + ]]: + raise NotImplementedError() + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + Union[ + platform.ListPrebuiltProcessorsResponse, + Awaitable[platform.ListPrebuiltProcessorsResponse] + ]]: + raise NotImplementedError() + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + Union[ + platform.Processor, + Awaitable[platform.Processor] + ]]: + raise NotImplementedError() + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AppPlatformTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/grpc.py new file mode 100644 index 000000000000..946212fa392d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/grpc.py @@ -0,0 +1,1036 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AppPlatformTransport, DEFAULT_CLIENT_INFO + + +class AppPlatformGrpcTransport(AppPlatformTransport): + """gRPC backend transport for AppPlatform. + + Service describing handlers for resources + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + platform.ListApplicationsResponse]: + r"""Return a callable for the list applications method over gRPC. + + Lists Applications in a given project and location. + + Returns: + Callable[[~.ListApplicationsRequest], + ~.ListApplicationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_applications' not in self._stubs: + self._stubs['list_applications'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListApplications', + request_serializer=platform.ListApplicationsRequest.serialize, + response_deserializer=platform.ListApplicationsResponse.deserialize, + ) + return self._stubs['list_applications'] + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + platform.Application]: + r"""Return a callable for the get application method over gRPC. + + Gets details of a single Application. + + Returns: + Callable[[~.GetApplicationRequest], + ~.Application]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_application' not in self._stubs: + self._stubs['get_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetApplication', + request_serializer=platform.GetApplicationRequest.serialize, + response_deserializer=platform.Application.deserialize, + ) + return self._stubs['get_application'] + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create application method over gRPC. + + Creates a new Application in a given project and + location. + + Returns: + Callable[[~.CreateApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application' not in self._stubs: + self._stubs['create_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateApplication', + request_serializer=platform.CreateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application'] + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update application method over gRPC. + + Updates the parameters of a single Application. + + Returns: + Callable[[~.UpdateApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application' not in self._stubs: + self._stubs['update_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateApplication', + request_serializer=platform.UpdateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application'] + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete application method over gRPC. + + Deletes a single Application. + + Returns: + Callable[[~.DeleteApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application' not in self._stubs: + self._stubs['delete_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteApplication', + request_serializer=platform.DeleteApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application'] + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the deploy application method over gRPC. + + Deploys a single Application. + + Returns: + Callable[[~.DeployApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_application' not in self._stubs: + self._stubs['deploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeployApplication', + request_serializer=platform.DeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_application'] + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the undeploy application method over gRPC. + + Undeploys a single Application. + + Returns: + Callable[[~.UndeployApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undeploy_application' not in self._stubs: + self._stubs['undeploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UndeployApplication', + request_serializer=platform.UndeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_application'] + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + operations_pb2.Operation]: + r"""Return a callable for the add application stream input method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.AddApplicationStreamInputRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_application_stream_input' not in self._stubs: + self._stubs['add_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/AddApplicationStreamInput', + request_serializer=platform.AddApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_application_stream_input'] + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove application stream + input method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.RemoveApplicationStreamInputRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_application_stream_input' not in self._stubs: + self._stubs['remove_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/RemoveApplicationStreamInput', + request_serializer=platform.RemoveApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_application_stream_input'] + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + operations_pb2.Operation]: + r"""Return a callable for the update application stream + input method over gRPC. + + Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + Returns: + Callable[[~.UpdateApplicationStreamInputRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_stream_input' not in self._stubs: + self._stubs['update_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateApplicationStreamInput', + request_serializer=platform.UpdateApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_stream_input'] + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + platform.ListInstancesResponse]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListInstances', + request_serializer=platform.ListInstancesRequest.serialize, + response_deserializer=platform.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + platform.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetInstance', + request_serializer=platform.GetInstanceRequest.serialize, + response_deserializer=platform.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the create application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.CreateApplicationInstancesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application_instances' not in self._stubs: + self._stubs['create_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateApplicationInstances', + request_serializer=platform.CreateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application_instances'] + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete application instances method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.DeleteApplicationInstancesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application_instances' not in self._stubs: + self._stubs['delete_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteApplicationInstances', + request_serializer=platform.DeleteApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application_instances'] + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the update application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.UpdateApplicationInstancesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_instances' not in self._stubs: + self._stubs['update_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateApplicationInstances', + request_serializer=platform.UpdateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_instances'] + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + platform.ListDraftsResponse]: + r"""Return a callable for the list drafts method over gRPC. + + Lists Drafts in a given project and location. + + Returns: + Callable[[~.ListDraftsRequest], + ~.ListDraftsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_drafts' not in self._stubs: + self._stubs['list_drafts'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListDrafts', + request_serializer=platform.ListDraftsRequest.serialize, + response_deserializer=platform.ListDraftsResponse.deserialize, + ) + return self._stubs['list_drafts'] + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + platform.Draft]: + r"""Return a callable for the get draft method over gRPC. + + Gets details of a single Draft. + + Returns: + Callable[[~.GetDraftRequest], + ~.Draft]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_draft' not in self._stubs: + self._stubs['get_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetDraft', + request_serializer=platform.GetDraftRequest.serialize, + response_deserializer=platform.Draft.deserialize, + ) + return self._stubs['get_draft'] + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + operations_pb2.Operation]: + r"""Return a callable for the create draft method over gRPC. + + Creates a new Draft in a given project and location. + + Returns: + Callable[[~.CreateDraftRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_draft' not in self._stubs: + self._stubs['create_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateDraft', + request_serializer=platform.CreateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_draft'] + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + operations_pb2.Operation]: + r"""Return a callable for the update draft method over gRPC. + + Updates the parameters of a single Draft. + + Returns: + Callable[[~.UpdateDraftRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_draft' not in self._stubs: + self._stubs['update_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateDraft', + request_serializer=platform.UpdateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_draft'] + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete draft method over gRPC. + + Deletes a single Draft. + + Returns: + Callable[[~.DeleteDraftRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_draft' not in self._stubs: + self._stubs['delete_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteDraft', + request_serializer=platform.DeleteDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_draft'] + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + platform.ListProcessorsResponse]: + r"""Return a callable for the list processors method over gRPC. + + Lists Processors in a given project and location. + + Returns: + Callable[[~.ListProcessorsRequest], + ~.ListProcessorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListProcessors', + request_serializer=platform.ListProcessorsRequest.serialize, + response_deserializer=platform.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + platform.ListPrebuiltProcessorsResponse]: + r"""Return a callable for the list prebuilt processors method over gRPC. + + ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + Returns: + Callable[[~.ListPrebuiltProcessorsRequest], + ~.ListPrebuiltProcessorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prebuilt_processors' not in self._stubs: + self._stubs['list_prebuilt_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListPrebuiltProcessors', + request_serializer=platform.ListPrebuiltProcessorsRequest.serialize, + response_deserializer=platform.ListPrebuiltProcessorsResponse.deserialize, + ) + return self._stubs['list_prebuilt_processors'] + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + platform.Processor]: + r"""Return a callable for the get processor method over gRPC. + + Gets details of a single Processor. + + Returns: + Callable[[~.GetProcessorRequest], + ~.Processor]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetProcessor', + request_serializer=platform.GetProcessorRequest.serialize, + response_deserializer=platform.Processor.deserialize, + ) + return self._stubs['get_processor'] + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the create processor method over gRPC. + + Creates a new Processor in a given project and + location. + + Returns: + Callable[[~.CreateProcessorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateProcessor', + request_serializer=platform.CreateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_processor'] + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the update processor method over gRPC. + + Updates the parameters of a single Processor. + + Returns: + Callable[[~.UpdateProcessorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_processor' not in self._stubs: + self._stubs['update_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateProcessor', + request_serializer=platform.UpdateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_processor'] + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes a single Processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteProcessor', + request_serializer=platform.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AppPlatformGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/grpc_asyncio.py new file mode 100644 index 000000000000..d6f1b401a6a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/grpc_asyncio.py @@ -0,0 +1,1171 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AppPlatformTransport, DEFAULT_CLIENT_INFO +from .grpc import AppPlatformGrpcTransport + + +class AppPlatformGrpcAsyncIOTransport(AppPlatformTransport): + """gRPC AsyncIO backend transport for AppPlatform. + + Service describing handlers for resources + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + Awaitable[platform.ListApplicationsResponse]]: + r"""Return a callable for the list applications method over gRPC. + + Lists Applications in a given project and location. + + Returns: + Callable[[~.ListApplicationsRequest], + Awaitable[~.ListApplicationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_applications' not in self._stubs: + self._stubs['list_applications'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListApplications', + request_serializer=platform.ListApplicationsRequest.serialize, + response_deserializer=platform.ListApplicationsResponse.deserialize, + ) + return self._stubs['list_applications'] + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + Awaitable[platform.Application]]: + r"""Return a callable for the get application method over gRPC. + + Gets details of a single Application. + + Returns: + Callable[[~.GetApplicationRequest], + Awaitable[~.Application]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_application' not in self._stubs: + self._stubs['get_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetApplication', + request_serializer=platform.GetApplicationRequest.serialize, + response_deserializer=platform.Application.deserialize, + ) + return self._stubs['get_application'] + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create application method over gRPC. + + Creates a new Application in a given project and + location. + + Returns: + Callable[[~.CreateApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application' not in self._stubs: + self._stubs['create_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateApplication', + request_serializer=platform.CreateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application'] + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update application method over gRPC. + + Updates the parameters of a single Application. + + Returns: + Callable[[~.UpdateApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application' not in self._stubs: + self._stubs['update_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateApplication', + request_serializer=platform.UpdateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application'] + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete application method over gRPC. + + Deletes a single Application. + + Returns: + Callable[[~.DeleteApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application' not in self._stubs: + self._stubs['delete_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteApplication', + request_serializer=platform.DeleteApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application'] + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the deploy application method over gRPC. + + Deploys a single Application. + + Returns: + Callable[[~.DeployApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_application' not in self._stubs: + self._stubs['deploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeployApplication', + request_serializer=platform.DeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_application'] + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the undeploy application method over gRPC. + + Undeploys a single Application. + + Returns: + Callable[[~.UndeployApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undeploy_application' not in self._stubs: + self._stubs['undeploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UndeployApplication', + request_serializer=platform.UndeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_application'] + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add application stream input method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.AddApplicationStreamInputRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_application_stream_input' not in self._stubs: + self._stubs['add_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/AddApplicationStreamInput', + request_serializer=platform.AddApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_application_stream_input'] + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove application stream + input method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.RemoveApplicationStreamInputRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_application_stream_input' not in self._stubs: + self._stubs['remove_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/RemoveApplicationStreamInput', + request_serializer=platform.RemoveApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_application_stream_input'] + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update application stream + input method over gRPC. + + Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + Returns: + Callable[[~.UpdateApplicationStreamInputRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_stream_input' not in self._stubs: + self._stubs['update_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateApplicationStreamInput', + request_serializer=platform.UpdateApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_stream_input'] + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + Awaitable[platform.ListInstancesResponse]]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListInstances', + request_serializer=platform.ListInstancesRequest.serialize, + response_deserializer=platform.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + Awaitable[platform.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetInstance', + request_serializer=platform.GetInstanceRequest.serialize, + response_deserializer=platform.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.CreateApplicationInstancesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application_instances' not in self._stubs: + self._stubs['create_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateApplicationInstances', + request_serializer=platform.CreateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application_instances'] + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete application instances method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.DeleteApplicationInstancesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application_instances' not in self._stubs: + self._stubs['delete_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteApplicationInstances', + request_serializer=platform.DeleteApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application_instances'] + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.UpdateApplicationInstancesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_instances' not in self._stubs: + self._stubs['update_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateApplicationInstances', + request_serializer=platform.UpdateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_instances'] + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + Awaitable[platform.ListDraftsResponse]]: + r"""Return a callable for the list drafts method over gRPC. + + Lists Drafts in a given project and location. + + Returns: + Callable[[~.ListDraftsRequest], + Awaitable[~.ListDraftsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_drafts' not in self._stubs: + self._stubs['list_drafts'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListDrafts', + request_serializer=platform.ListDraftsRequest.serialize, + response_deserializer=platform.ListDraftsResponse.deserialize, + ) + return self._stubs['list_drafts'] + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + Awaitable[platform.Draft]]: + r"""Return a callable for the get draft method over gRPC. + + Gets details of a single Draft. + + Returns: + Callable[[~.GetDraftRequest], + Awaitable[~.Draft]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_draft' not in self._stubs: + self._stubs['get_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetDraft', + request_serializer=platform.GetDraftRequest.serialize, + response_deserializer=platform.Draft.deserialize, + ) + return self._stubs['get_draft'] + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create draft method over gRPC. + + Creates a new Draft in a given project and location. + + Returns: + Callable[[~.CreateDraftRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_draft' not in self._stubs: + self._stubs['create_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateDraft', + request_serializer=platform.CreateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_draft'] + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update draft method over gRPC. + + Updates the parameters of a single Draft. + + Returns: + Callable[[~.UpdateDraftRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_draft' not in self._stubs: + self._stubs['update_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateDraft', + request_serializer=platform.UpdateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_draft'] + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete draft method over gRPC. + + Deletes a single Draft. + + Returns: + Callable[[~.DeleteDraftRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_draft' not in self._stubs: + self._stubs['delete_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteDraft', + request_serializer=platform.DeleteDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_draft'] + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + Awaitable[platform.ListProcessorsResponse]]: + r"""Return a callable for the list processors method over gRPC. + + Lists Processors in a given project and location. + + Returns: + Callable[[~.ListProcessorsRequest], + Awaitable[~.ListProcessorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListProcessors', + request_serializer=platform.ListProcessorsRequest.serialize, + response_deserializer=platform.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + Awaitable[platform.ListPrebuiltProcessorsResponse]]: + r"""Return a callable for the list prebuilt processors method over gRPC. + + ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + Returns: + Callable[[~.ListPrebuiltProcessorsRequest], + Awaitable[~.ListPrebuiltProcessorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prebuilt_processors' not in self._stubs: + self._stubs['list_prebuilt_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/ListPrebuiltProcessors', + request_serializer=platform.ListPrebuiltProcessorsRequest.serialize, + response_deserializer=platform.ListPrebuiltProcessorsResponse.deserialize, + ) + return self._stubs['list_prebuilt_processors'] + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + Awaitable[platform.Processor]]: + r"""Return a callable for the get processor method over gRPC. + + Gets details of a single Processor. + + Returns: + Callable[[~.GetProcessorRequest], + Awaitable[~.Processor]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/GetProcessor', + request_serializer=platform.GetProcessorRequest.serialize, + response_deserializer=platform.Processor.deserialize, + ) + return self._stubs['get_processor'] + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create processor method over gRPC. + + Creates a new Processor in a given project and + location. + + Returns: + Callable[[~.CreateProcessorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/CreateProcessor', + request_serializer=platform.CreateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_processor'] + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update processor method over gRPC. + + Updates the parameters of a single Processor. + + Returns: + Callable[[~.UpdateProcessorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_processor' not in self._stubs: + self._stubs['update_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/UpdateProcessor', + request_serializer=platform.UpdateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_processor'] + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes a single Processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.AppPlatform/DeleteProcessor', + request_serializer=platform.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_applications: gapic_v1.method_async.wrap_method( + self.list_applications, + default_timeout=None, + client_info=client_info, + ), + self.get_application: gapic_v1.method_async.wrap_method( + self.get_application, + default_timeout=None, + client_info=client_info, + ), + self.create_application: gapic_v1.method_async.wrap_method( + self.create_application, + default_timeout=None, + client_info=client_info, + ), + self.update_application: gapic_v1.method_async.wrap_method( + self.update_application, + default_timeout=None, + client_info=client_info, + ), + self.delete_application: gapic_v1.method_async.wrap_method( + self.delete_application, + default_timeout=None, + client_info=client_info, + ), + self.deploy_application: gapic_v1.method_async.wrap_method( + self.deploy_application, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_application: gapic_v1.method_async.wrap_method( + self.undeploy_application, + default_timeout=None, + client_info=client_info, + ), + self.add_application_stream_input: gapic_v1.method_async.wrap_method( + self.add_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.remove_application_stream_input: gapic_v1.method_async.wrap_method( + self.remove_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.update_application_stream_input: gapic_v1.method_async.wrap_method( + self.update_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method_async.wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method_async.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_application_instances: gapic_v1.method_async.wrap_method( + self.create_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.delete_application_instances: gapic_v1.method_async.wrap_method( + self.delete_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.update_application_instances: gapic_v1.method_async.wrap_method( + self.update_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.list_drafts: gapic_v1.method_async.wrap_method( + self.list_drafts, + default_timeout=None, + client_info=client_info, + ), + self.get_draft: gapic_v1.method_async.wrap_method( + self.get_draft, + default_timeout=None, + client_info=client_info, + ), + self.create_draft: gapic_v1.method_async.wrap_method( + self.create_draft, + default_timeout=None, + client_info=client_info, + ), + self.update_draft: gapic_v1.method_async.wrap_method( + self.update_draft, + default_timeout=None, + client_info=client_info, + ), + self.delete_draft: gapic_v1.method_async.wrap_method( + self.delete_draft, + default_timeout=None, + client_info=client_info, + ), + self.list_processors: gapic_v1.method_async.wrap_method( + self.list_processors, + default_timeout=None, + client_info=client_info, + ), + self.list_prebuilt_processors: gapic_v1.method_async.wrap_method( + self.list_prebuilt_processors, + default_timeout=None, + client_info=client_info, + ), + self.get_processor: gapic_v1.method_async.wrap_method( + self.get_processor, + default_timeout=None, + client_info=client_info, + ), + self.create_processor: gapic_v1.method_async.wrap_method( + self.create_processor, + default_timeout=None, + client_info=client_info, + ), + self.update_processor: gapic_v1.method_async.wrap_method( + self.update_processor, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor: gapic_v1.method_async.wrap_method( + self.delete_processor, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'AppPlatformGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/rest.py new file mode 100644 index 000000000000..4091e30b4c55 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/app_platform/transports/rest.py @@ -0,0 +1,3625 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1.types import platform +from google.longrunning import operations_pb2 # type: ignore + +from .base import AppPlatformTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class AppPlatformRestInterceptor: + """Interceptor for AppPlatform. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AppPlatformRestTransport. + + .. code-block:: python + class MyCustomAppPlatformInterceptor(AppPlatformRestInterceptor): + def pre_add_application_stream_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_application_stream_input(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_application_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_application_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_application_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_application_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_deploy_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_deploy_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_applications(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_applications(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_drafts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_drafts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_prebuilt_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_prebuilt_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_application_stream_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_application_stream_input(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undeploy_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undeploy_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_application_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_application_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_application_stream_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_application_stream_input(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_processor(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AppPlatformRestTransport(interceptor=MyCustomAppPlatformInterceptor()) + client = AppPlatformClient(transport=transport) + + + """ + def pre_add_application_stream_input(self, request: platform.AddApplicationStreamInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.AddApplicationStreamInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for add_application_stream_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_add_application_stream_input(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for add_application_stream_input + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_application(self, request: platform.CreateApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_application_instances(self, request: platform.CreateApplicationInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateApplicationInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_application_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_application_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_application_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_draft(self, request: platform.CreateDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_draft(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_processor(self, request: platform.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_application(self, request: platform.DeleteApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_application_instances(self, request: platform.DeleteApplicationInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteApplicationInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_application_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_application_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_application_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_draft(self, request: platform.DeleteDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_draft(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_processor(self, request: platform.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_deploy_application(self, request: platform.DeployApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeployApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for deploy_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_deploy_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for deploy_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_application(self, request: platform.GetApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_application(self, response: platform.Application) -> platform.Application: + """Post-rpc interceptor for get_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_draft(self, request: platform.GetDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_draft(self, response: platform.Draft) -> platform.Draft: + """Post-rpc interceptor for get_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_instance(self, request: platform.GetInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_instance(self, response: platform.Instance) -> platform.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_processor(self, request: platform.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_processor(self, response: platform.Processor) -> platform.Processor: + """Post-rpc interceptor for get_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_applications(self, request: platform.ListApplicationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListApplicationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_applications + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_applications(self, response: platform.ListApplicationsResponse) -> platform.ListApplicationsResponse: + """Post-rpc interceptor for list_applications + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_drafts(self, request: platform.ListDraftsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListDraftsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_drafts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_drafts(self, response: platform.ListDraftsResponse) -> platform.ListDraftsResponse: + """Post-rpc interceptor for list_drafts + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_instances(self, request: platform.ListInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_instances(self, response: platform.ListInstancesResponse) -> platform.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_prebuilt_processors(self, request: platform.ListPrebuiltProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListPrebuiltProcessorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_prebuilt_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_prebuilt_processors(self, response: platform.ListPrebuiltProcessorsResponse) -> platform.ListPrebuiltProcessorsResponse: + """Post-rpc interceptor for list_prebuilt_processors + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_processors(self, request: platform.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListProcessorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_processors(self, response: platform.ListProcessorsResponse) -> platform.ListProcessorsResponse: + """Post-rpc interceptor for list_processors + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_remove_application_stream_input(self, request: platform.RemoveApplicationStreamInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.RemoveApplicationStreamInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for remove_application_stream_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_remove_application_stream_input(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for remove_application_stream_input + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_undeploy_application(self, request: platform.UndeployApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UndeployApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undeploy_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_undeploy_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for undeploy_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_application(self, request: platform.UpdateApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_application_instances(self, request: platform.UpdateApplicationInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateApplicationInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_application_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_application_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_application_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_application_stream_input(self, request: platform.UpdateApplicationStreamInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateApplicationStreamInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_application_stream_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_application_stream_input(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_application_stream_input + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_draft(self, request: platform.UpdateDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_draft(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_processor(self, request: platform.UpdateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AppPlatformRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AppPlatformRestInterceptor + + +class AppPlatformRestTransport(AppPlatformTransport): + """REST backend transport for AppPlatform. + + Service describing handlers for resources + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[AppPlatformRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AppPlatformRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _AddApplicationStreamInput(AppPlatformRestStub): + def __hash__(self): + return hash("AddApplicationStreamInput") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.AddApplicationStreamInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the add application stream + input method over HTTP. + + Args: + request (~.platform.AddApplicationStreamInputRequest): + The request object. Message for adding stream input to an + Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:addStreamInput', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_add_application_stream_input(request, metadata) + pb_request = platform.AddApplicationStreamInputRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_add_application_stream_input(resp) + return resp + + class _CreateApplication(AppPlatformRestStub): + def __hash__(self): + return hash("CreateApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "applicationId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create application method over HTTP. + + Args: + request (~.platform.CreateApplicationRequest): + The request object. Message for creating a Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/applications', + 'body': 'application', + }, + ] + request, metadata = self._interceptor.pre_create_application(request, metadata) + pb_request = platform.CreateApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_application(resp) + return resp + + class _CreateApplicationInstances(AppPlatformRestStub): + def __hash__(self): + return hash("CreateApplicationInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateApplicationInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create application + instances method over HTTP. + + Args: + request (~.platform.CreateApplicationInstancesRequest): + The request object. Message for adding stream input to an + Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:createApplicationInstances', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_create_application_instances(request, metadata) + pb_request = platform.CreateApplicationInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_application_instances(resp) + return resp + + class _CreateDraft(AppPlatformRestStub): + def __hash__(self): + return hash("CreateDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "draftId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create draft method over HTTP. + + Args: + request (~.platform.CreateDraftRequest): + The request object. Message for creating a Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/applications/*}/drafts', + 'body': 'draft', + }, + ] + request, metadata = self._interceptor.pre_create_draft(request, metadata) + pb_request = platform.CreateDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_draft(resp) + return resp + + class _CreateProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("CreateProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "processorId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create processor method over HTTP. + + Args: + request (~.platform.CreateProcessorRequest): + The request object. Message for creating a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/processors', + 'body': 'processor', + }, + ] + request, metadata = self._interceptor.pre_create_processor(request, metadata) + pb_request = platform.CreateProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_processor(resp) + return resp + + class _DeleteApplication(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete application method over HTTP. + + Args: + request (~.platform.DeleteApplicationRequest): + The request object. Message for deleting an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_application(request, metadata) + pb_request = platform.DeleteApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_application(resp) + return resp + + class _DeleteApplicationInstances(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteApplicationInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteApplicationInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete application + instances method over HTTP. + + Args: + request (~.platform.DeleteApplicationInstancesRequest): + The request object. Message for removing stream input + from an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:deleteApplicationInstances', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_delete_application_instances(request, metadata) + pb_request = platform.DeleteApplicationInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_application_instances(resp) + return resp + + class _DeleteDraft(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete draft method over HTTP. + + Args: + request (~.platform.DeleteDraftRequest): + The request object. Message for deleting a Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/applications/*/drafts/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_draft(request, metadata) + pb_request = platform.DeleteDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_draft(resp) + return resp + + class _DeleteProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete processor method over HTTP. + + Args: + request (~.platform.DeleteProcessorRequest): + The request object. Message for deleting a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_processor(request, metadata) + pb_request = platform.DeleteProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_processor(resp) + return resp + + class _DeployApplication(AppPlatformRestStub): + def __hash__(self): + return hash("DeployApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeployApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the deploy application method over HTTP. + + Args: + request (~.platform.DeployApplicationRequest): + The request object. Message for deploying an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:deploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_deploy_application(request, metadata) + pb_request = platform.DeployApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_deploy_application(resp) + return resp + + class _GetApplication(AppPlatformRestStub): + def __hash__(self): + return hash("GetApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Application: + r"""Call the get application method over HTTP. + + Args: + request (~.platform.GetApplicationRequest): + The request object. Message for getting a Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Application: + Message describing Application object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}', + }, + ] + request, metadata = self._interceptor.pre_get_application(request, metadata) + pb_request = platform.GetApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Application() + pb_resp = platform.Application.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_application(resp) + return resp + + class _GetDraft(AppPlatformRestStub): + def __hash__(self): + return hash("GetDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Draft: + r"""Call the get draft method over HTTP. + + Args: + request (~.platform.GetDraftRequest): + The request object. Message for getting a Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Draft: + Message describing Draft object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/applications/*/drafts/*}', + }, + ] + request, metadata = self._interceptor.pre_get_draft(request, metadata) + pb_request = platform.GetDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Draft() + pb_resp = platform.Draft.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_draft(resp) + return resp + + class _GetInstance(AppPlatformRestStub): + def __hash__(self): + return hash("GetInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.platform.GetInstanceRequest): + The request object. Message for getting a Instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Instance: + Message describing Instance object + Next ID: 12 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/applications/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = platform.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Instance() + pb_resp = platform.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + class _GetProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("GetProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Processor: + r"""Call the get processor method over HTTP. + + Args: + request (~.platform.GetProcessorRequest): + The request object. Message for getting a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Processor: + Message describing Processor object. + Next ID: 19 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor(request, metadata) + pb_request = platform.GetProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Processor() + pb_resp = platform.Processor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor(resp) + return resp + + class _ListApplications(AppPlatformRestStub): + def __hash__(self): + return hash("ListApplications") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListApplicationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListApplicationsResponse: + r"""Call the list applications method over HTTP. + + Args: + request (~.platform.ListApplicationsRequest): + The request object. Message for requesting list of + Applications. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListApplicationsResponse: + Message for response to listing + Applications. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/applications', + }, + ] + request, metadata = self._interceptor.pre_list_applications(request, metadata) + pb_request = platform.ListApplicationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListApplicationsResponse() + pb_resp = platform.ListApplicationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_applications(resp) + return resp + + class _ListDrafts(AppPlatformRestStub): + def __hash__(self): + return hash("ListDrafts") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListDraftsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListDraftsResponse: + r"""Call the list drafts method over HTTP. + + Args: + request (~.platform.ListDraftsRequest): + The request object. Message for requesting list of + Drafts. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListDraftsResponse: + Message for response to listing + Drafts. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/applications/*}/drafts', + }, + ] + request, metadata = self._interceptor.pre_list_drafts(request, metadata) + pb_request = platform.ListDraftsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListDraftsResponse() + pb_resp = platform.ListDraftsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_drafts(resp) + return resp + + class _ListInstances(AppPlatformRestStub): + def __hash__(self): + return hash("ListInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.platform.ListInstancesRequest): + The request object. Message for requesting list of + Instances. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListInstancesResponse: + Message for response to listing + Instances. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/applications/*}/instances', + }, + ] + request, metadata = self._interceptor.pre_list_instances(request, metadata) + pb_request = platform.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListInstancesResponse() + pb_resp = platform.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_instances(resp) + return resp + + class _ListPrebuiltProcessors(AppPlatformRestStub): + def __hash__(self): + return hash("ListPrebuiltProcessors") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListPrebuiltProcessorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListPrebuiltProcessorsResponse: + r"""Call the list prebuilt processors method over HTTP. + + Args: + request (~.platform.ListPrebuiltProcessorsRequest): + The request object. Request Message for listing Prebuilt + Processors. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListPrebuiltProcessorsResponse: + Response Message for listing Prebuilt + Processors. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/processors:prebuilt', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_list_prebuilt_processors(request, metadata) + pb_request = platform.ListPrebuiltProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListPrebuiltProcessorsResponse() + pb_resp = platform.ListPrebuiltProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_prebuilt_processors(resp) + return resp + + class _ListProcessors(AppPlatformRestStub): + def __hash__(self): + return hash("ListProcessors") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListProcessorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListProcessorsResponse: + r"""Call the list processors method over HTTP. + + Args: + request (~.platform.ListProcessorsRequest): + The request object. Message for requesting list of + Processors. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListProcessorsResponse: + Message for response to listing + Processors. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/processors', + }, + ] + request, metadata = self._interceptor.pre_list_processors(request, metadata) + pb_request = platform.ListProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListProcessorsResponse() + pb_resp = platform.ListProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processors(resp) + return resp + + class _RemoveApplicationStreamInput(AppPlatformRestStub): + def __hash__(self): + return hash("RemoveApplicationStreamInput") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.RemoveApplicationStreamInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the remove application stream + input method over HTTP. + + Args: + request (~.platform.RemoveApplicationStreamInputRequest): + The request object. Message for removing stream input + from an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:removeStreamInput', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_remove_application_stream_input(request, metadata) + pb_request = platform.RemoveApplicationStreamInputRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_remove_application_stream_input(resp) + return resp + + class _UndeployApplication(AppPlatformRestStub): + def __hash__(self): + return hash("UndeployApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UndeployApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the undeploy application method over HTTP. + + Args: + request (~.platform.UndeployApplicationRequest): + The request object. Message for undeploying an + Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:undeploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_undeploy_application(request, metadata) + pb_request = platform.UndeployApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undeploy_application(resp) + return resp + + class _UpdateApplication(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update application method over HTTP. + + Args: + request (~.platform.UpdateApplicationRequest): + The request object. Message for updating an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{application.name=projects/*/locations/*/applications/*}', + 'body': 'application', + }, + ] + request, metadata = self._interceptor.pre_update_application(request, metadata) + pb_request = platform.UpdateApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_application(resp) + return resp + + class _UpdateApplicationInstances(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateApplicationInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateApplicationInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update application + instances method over HTTP. + + Args: + request (~.platform.UpdateApplicationInstancesRequest): + The request object. Message for updating an + ApplicationInstance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:updateApplicationInstances', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_update_application_instances(request, metadata) + pb_request = platform.UpdateApplicationInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_application_instances(resp) + return resp + + class _UpdateApplicationStreamInput(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateApplicationStreamInput") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateApplicationStreamInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update application stream + input method over HTTP. + + Args: + request (~.platform.UpdateApplicationStreamInputRequest): + The request object. Message for updating stream input to + an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/applications/*}:updateStreamInput', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_update_application_stream_input(request, metadata) + pb_request = platform.UpdateApplicationStreamInputRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_application_stream_input(resp) + return resp + + class _UpdateDraft(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update draft method over HTTP. + + Args: + request (~.platform.UpdateDraftRequest): + The request object. Message for updating a Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{draft.name=projects/*/locations/*/applications/*/drafts/*}', + 'body': 'draft', + }, + ] + request, metadata = self._interceptor.pre_update_draft(request, metadata) + pb_request = platform.UpdateDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_draft(resp) + return resp + + class _UpdateProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update processor method over HTTP. + + Args: + request (~.platform.UpdateProcessorRequest): + The request object. Message for updating a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{processor.name=projects/*/locations/*/processors/*}', + 'body': 'processor', + }, + ] + request, metadata = self._interceptor.pre_update_processor(request, metadata) + pb_request = platform.UpdateProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_processor(resp) + return resp + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AddApplicationStreamInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApplicationInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApplicationInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeployApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + platform.Application]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + platform.Draft]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + platform.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + platform.Processor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + platform.ListApplicationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApplications(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + platform.ListDraftsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDrafts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + platform.ListInstancesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + platform.ListPrebuiltProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPrebuiltProcessors(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + platform.ListProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveApplicationStreamInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeployApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApplicationInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApplicationStreamInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AppPlatformRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/__init__.py new file mode 100644 index 000000000000..fad7dd2d8d5e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 HealthCheckServiceClient +from .async_client import HealthCheckServiceAsyncClient + +__all__ = ( + 'HealthCheckServiceClient', + 'HealthCheckServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/async_client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/async_client.py new file mode 100644 index 000000000000..c3e9af084f73 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/async_client.py @@ -0,0 +1,541 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import health_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import HealthCheckServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import HealthCheckServiceGrpcAsyncIOTransport +from .client import HealthCheckServiceClient + + +class HealthCheckServiceAsyncClient: + """HealthCheckService provides an interface for Vertex AI Vision + Cluster Health Check. + """ + + _client: HealthCheckServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = HealthCheckServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = HealthCheckServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = HealthCheckServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = HealthCheckServiceClient._DEFAULT_UNIVERSE + + cluster_path = staticmethod(HealthCheckServiceClient.cluster_path) + parse_cluster_path = staticmethod(HealthCheckServiceClient.parse_cluster_path) + common_billing_account_path = staticmethod(HealthCheckServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(HealthCheckServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(HealthCheckServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(HealthCheckServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(HealthCheckServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(HealthCheckServiceClient.parse_common_organization_path) + common_project_path = staticmethod(HealthCheckServiceClient.common_project_path) + parse_common_project_path = staticmethod(HealthCheckServiceClient.parse_common_project_path) + common_location_path = staticmethod(HealthCheckServiceClient.common_location_path) + parse_common_location_path = staticmethod(HealthCheckServiceClient.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: + HealthCheckServiceAsyncClient: The constructed client. + """ + return HealthCheckServiceClient.from_service_account_info.__func__(HealthCheckServiceAsyncClient, 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: + HealthCheckServiceAsyncClient: The constructed client. + """ + return HealthCheckServiceClient.from_service_account_file.__func__(HealthCheckServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return HealthCheckServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> HealthCheckServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HealthCheckServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(HealthCheckServiceClient).get_transport_class, type(HealthCheckServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, HealthCheckServiceTransport, Callable[..., HealthCheckServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the health check service async 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 (Optional[Union[str,HealthCheckServiceTransport,Callable[..., HealthCheckServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the HealthCheckServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = HealthCheckServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def health_check(self, + request: Optional[Union[health_service.HealthCheckRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> health_service.HealthCheckResponse: + r"""HealthCheck method checks the health status of the + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_health_check(): + # Create a client + client = visionai_v1.HealthCheckServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.HealthCheckRequest( + ) + + # Make the request + response = await client.health_check(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.HealthCheckRequest, dict]]): + The request object. HealthCheckRequest is the request + message for Check. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.HealthCheckResponse: + HealthCheckResponse is the response + message for Check. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, health_service.HealthCheckRequest): + request = health_service.HealthCheckRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.health_check] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster", request.cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "HealthCheckServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "HealthCheckServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/client.py new file mode 100644 index 000000000000..408d490d6d6e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/client.py @@ -0,0 +1,901 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import health_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import HealthCheckServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import HealthCheckServiceGrpcTransport +from .transports.grpc_asyncio import HealthCheckServiceGrpcAsyncIOTransport +from .transports.rest import HealthCheckServiceRestTransport + + +class HealthCheckServiceClientMeta(type): + """Metaclass for the HealthCheckService 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[HealthCheckServiceTransport]] + _transport_registry["grpc"] = HealthCheckServiceGrpcTransport + _transport_registry["grpc_asyncio"] = HealthCheckServiceGrpcAsyncIOTransport + _transport_registry["rest"] = HealthCheckServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[HealthCheckServiceTransport]: + """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 HealthCheckServiceClient(metaclass=HealthCheckServiceClientMeta): + """HealthCheckService provides an interface for Vertex AI Vision + Cluster Health Check. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + HealthCheckServiceClient: 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: + HealthCheckServiceClient: 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) -> HealthCheckServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HealthCheckServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = HealthCheckServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = HealthCheckServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = HealthCheckServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = HealthCheckServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = HealthCheckServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + HealthCheckServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, HealthCheckServiceTransport, Callable[..., HealthCheckServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the health check service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,HealthCheckServiceTransport,Callable[..., HealthCheckServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the HealthCheckServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = HealthCheckServiceClient._read_environment_variables() + self._client_cert_source = HealthCheckServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = HealthCheckServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, HealthCheckServiceTransport) + if transport_provided: + # transport is a HealthCheckServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(HealthCheckServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + HealthCheckServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[HealthCheckServiceTransport], Callable[..., HealthCheckServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., HealthCheckServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def health_check(self, + request: Optional[Union[health_service.HealthCheckRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> health_service.HealthCheckResponse: + r"""HealthCheck method checks the health status of the + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_health_check(): + # Create a client + client = visionai_v1.HealthCheckServiceClient() + + # Initialize request argument(s) + request = visionai_v1.HealthCheckRequest( + ) + + # Make the request + response = client.health_check(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.HealthCheckRequest, dict]): + The request object. HealthCheckRequest is the request + message for Check. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.HealthCheckResponse: + HealthCheckResponse is the response + message for Check. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, health_service.HealthCheckRequest): + request = health_service.HealthCheckRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.health_check] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster", request.cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "HealthCheckServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "HealthCheckServiceClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/__init__.py new file mode 100644 index 000000000000..8db700965e37 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 HealthCheckServiceTransport +from .grpc import HealthCheckServiceGrpcTransport +from .grpc_asyncio import HealthCheckServiceGrpcAsyncIOTransport +from .rest import HealthCheckServiceRestTransport +from .rest import HealthCheckServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[HealthCheckServiceTransport]] +_transport_registry['grpc'] = HealthCheckServiceGrpcTransport +_transport_registry['grpc_asyncio'] = HealthCheckServiceGrpcAsyncIOTransport +_transport_registry['rest'] = HealthCheckServiceRestTransport + +__all__ = ( + 'HealthCheckServiceTransport', + 'HealthCheckServiceGrpcTransport', + 'HealthCheckServiceGrpcAsyncIOTransport', + 'HealthCheckServiceRestTransport', + 'HealthCheckServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/base.py new file mode 100644 index 000000000000..c16bbbd2dc68 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/base.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import health_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class HealthCheckServiceTransport(abc.ABC): + """Abstract transport class for HealthCheckService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.health_check: gapic_v1.method.wrap_method( + self.health_check, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def health_check(self) -> Callable[ + [health_service.HealthCheckRequest], + Union[ + health_service.HealthCheckResponse, + Awaitable[health_service.HealthCheckResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'HealthCheckServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/grpc.py new file mode 100644 index 000000000000..19406e4005cf --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/grpc.py @@ -0,0 +1,347 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import health_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import HealthCheckServiceTransport, DEFAULT_CLIENT_INFO + + +class HealthCheckServiceGrpcTransport(HealthCheckServiceTransport): + """gRPC backend transport for HealthCheckService. + + HealthCheckService provides an interface for Vertex AI Vision + Cluster Health Check. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance 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 isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[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 health_check(self) -> Callable[ + [health_service.HealthCheckRequest], + health_service.HealthCheckResponse]: + r"""Return a callable for the health check method over gRPC. + + HealthCheck method checks the health status of the + cluster. + + Returns: + Callable[[~.HealthCheckRequest], + ~.HealthCheckResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'health_check' not in self._stubs: + self._stubs['health_check'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.HealthCheckService/HealthCheck', + request_serializer=health_service.HealthCheckRequest.serialize, + response_deserializer=health_service.HealthCheckResponse.deserialize, + ) + return self._stubs['health_check'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'HealthCheckServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ecfcdd44f788 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/grpc_asyncio.py @@ -0,0 +1,357 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import health_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import HealthCheckServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import HealthCheckServiceGrpcTransport + + +class HealthCheckServiceGrpcAsyncIOTransport(HealthCheckServiceTransport): + """gRPC AsyncIO backend transport for HealthCheckService. + + HealthCheckService provides an interface for Vertex AI Vision + Cluster Health Check. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance 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 isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def health_check(self) -> Callable[ + [health_service.HealthCheckRequest], + Awaitable[health_service.HealthCheckResponse]]: + r"""Return a callable for the health check method over gRPC. + + HealthCheck method checks the health status of the + cluster. + + Returns: + Callable[[~.HealthCheckRequest], + Awaitable[~.HealthCheckResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'health_check' not in self._stubs: + self._stubs['health_check'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.HealthCheckService/HealthCheck', + request_serializer=health_service.HealthCheckRequest.serialize, + response_deserializer=health_service.HealthCheckResponse.deserialize, + ) + return self._stubs['health_check'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.health_check: gapic_v1.method_async.wrap_method( + self.health_check, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'HealthCheckServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/rest.py new file mode 100644 index 000000000000..4f58edc2096d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/health_check_service/transports/rest.py @@ -0,0 +1,647 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1.types import health_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import HealthCheckServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class HealthCheckServiceRestInterceptor: + """Interceptor for HealthCheckService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the HealthCheckServiceRestTransport. + + .. code-block:: python + class MyCustomHealthCheckServiceInterceptor(HealthCheckServiceRestInterceptor): + def pre_health_check(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_health_check(self, response): + logging.log(f"Received response: {response}") + return response + + transport = HealthCheckServiceRestTransport(interceptor=MyCustomHealthCheckServiceInterceptor()) + client = HealthCheckServiceClient(transport=transport) + + + """ + def pre_health_check(self, request: health_service.HealthCheckRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[health_service.HealthCheckRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for health_check + + Override in a subclass to manipulate the request or metadata + before they are sent to the HealthCheckService server. + """ + return request, metadata + + def post_health_check(self, response: health_service.HealthCheckResponse) -> health_service.HealthCheckResponse: + """Post-rpc interceptor for health_check + + Override in a subclass to manipulate the response + after it is returned by the HealthCheckService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the HealthCheckService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the HealthCheckService server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the HealthCheckService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the HealthCheckService server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the HealthCheckService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the HealthCheckService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the HealthCheckService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the HealthCheckService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class HealthCheckServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: HealthCheckServiceRestInterceptor + + +class HealthCheckServiceRestTransport(HealthCheckServiceTransport): + """REST backend transport for HealthCheckService. + + HealthCheckService provides an interface for Vertex AI Vision + Cluster Health Check. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[HealthCheckServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or HealthCheckServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _HealthCheck(HealthCheckServiceRestStub): + def __hash__(self): + return hash("HealthCheck") + + def __call__(self, + request: health_service.HealthCheckRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> health_service.HealthCheckResponse: + r"""Call the health check method over HTTP. + + Args: + request (~.health_service.HealthCheckRequest): + The request object. HealthCheckRequest is the request + message for Check. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.health_service.HealthCheckResponse: + HealthCheckResponse is the response + message for Check. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{cluster=projects/*/locations/*/clusters/*}:healthCheck', + }, + ] + request, metadata = self._interceptor.pre_health_check(request, metadata) + pb_request = health_service.HealthCheckRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = health_service.HealthCheckResponse() + pb_resp = health_service.HealthCheckResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_health_check(resp) + return resp + + @property + def health_check(self) -> Callable[ + [health_service.HealthCheckRequest], + health_service.HealthCheckResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._HealthCheck(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(HealthCheckServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(HealthCheckServiceRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(HealthCheckServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(HealthCheckServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'HealthCheckServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/__init__.py new file mode 100644 index 000000000000..4d7712a4fda6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LiveVideoAnalyticsClient +from .async_client import LiveVideoAnalyticsAsyncClient + +__all__ = ( + 'LiveVideoAnalyticsClient', + 'LiveVideoAnalyticsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/async_client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/async_client.py new file mode 100644 index 000000000000..cb10b22e1722 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/async_client.py @@ -0,0 +1,2653 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.live_video_analytics import pagers +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import lva +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LiveVideoAnalyticsGrpcAsyncIOTransport +from .client import LiveVideoAnalyticsClient + + +class LiveVideoAnalyticsAsyncClient: + """Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + """ + + _client: LiveVideoAnalyticsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LiveVideoAnalyticsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + + analysis_path = staticmethod(LiveVideoAnalyticsClient.analysis_path) + parse_analysis_path = staticmethod(LiveVideoAnalyticsClient.parse_analysis_path) + cluster_path = staticmethod(LiveVideoAnalyticsClient.cluster_path) + parse_cluster_path = staticmethod(LiveVideoAnalyticsClient.parse_cluster_path) + operator_path = staticmethod(LiveVideoAnalyticsClient.operator_path) + parse_operator_path = staticmethod(LiveVideoAnalyticsClient.parse_operator_path) + process_path = staticmethod(LiveVideoAnalyticsClient.process_path) + parse_process_path = staticmethod(LiveVideoAnalyticsClient.parse_process_path) + common_billing_account_path = staticmethod(LiveVideoAnalyticsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LiveVideoAnalyticsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LiveVideoAnalyticsClient.common_folder_path) + parse_common_folder_path = staticmethod(LiveVideoAnalyticsClient.parse_common_folder_path) + common_organization_path = staticmethod(LiveVideoAnalyticsClient.common_organization_path) + parse_common_organization_path = staticmethod(LiveVideoAnalyticsClient.parse_common_organization_path) + common_project_path = staticmethod(LiveVideoAnalyticsClient.common_project_path) + parse_common_project_path = staticmethod(LiveVideoAnalyticsClient.parse_common_project_path) + common_location_path = staticmethod(LiveVideoAnalyticsClient.common_location_path) + parse_common_location_path = staticmethod(LiveVideoAnalyticsClient.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: + LiveVideoAnalyticsAsyncClient: The constructed client. + """ + return LiveVideoAnalyticsClient.from_service_account_info.__func__(LiveVideoAnalyticsAsyncClient, 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: + LiveVideoAnalyticsAsyncClient: The constructed client. + """ + return LiveVideoAnalyticsClient.from_service_account_file.__func__(LiveVideoAnalyticsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LiveVideoAnalyticsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LiveVideoAnalyticsTransport: + """Returns the transport used by the client instance. + + Returns: + LiveVideoAnalyticsTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(LiveVideoAnalyticsClient).get_transport_class, type(LiveVideoAnalyticsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LiveVideoAnalyticsTransport, Callable[..., LiveVideoAnalyticsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the live video analytics async 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 (Optional[Union[str,LiveVideoAnalyticsTransport,Callable[..., LiveVideoAnalyticsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LiveVideoAnalyticsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = LiveVideoAnalyticsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_public_operators(self, + request: Optional[Union[lva_service.ListPublicOperatorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPublicOperatorsAsyncPager: + r"""ListPublicOperators returns all the operators in + public registry. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_public_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListPublicOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_public_operators(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListPublicOperatorsRequest, dict]]): + The request object. Request message of + ListPublicOperatorsRequest API. + parent (:class:`str`): + Required. Parent value for + ListPublicOperatorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListPublicOperatorsAsyncPager: + Response message of + ListPublicOperators API. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListPublicOperatorsRequest): + request = lva_service.ListPublicOperatorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_public_operators] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListPublicOperatorsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def resolve_operator_info(self, + request: Optional[Union[lva_service.ResolveOperatorInfoRequest, dict]] = None, + *, + parent: Optional[str] = None, + queries: Optional[MutableSequence[lva_service.OperatorQuery]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_service.ResolveOperatorInfoResponse: + r"""ResolveOperatorInfo returns the operator information + based on the request. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_resolve_operator_info(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + queries = visionai_v1.OperatorQuery() + queries.operator = "operator_value" + + request = visionai_v1.ResolveOperatorInfoRequest( + parent="parent_value", + queries=queries, + ) + + # Make the request + response = await client.resolve_operator_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ResolveOperatorInfoRequest, dict]]): + The request object. Request message for querying operator + info. + parent (:class:`str`): + Required. Parent value for + ResolveOperatorInfoRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + queries (:class:`MutableSequence[google.cloud.visionai_v1.types.OperatorQuery]`): + Required. The operator queries. + This corresponds to the ``queries`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ResolveOperatorInfoResponse: + Response message of + ResolveOperatorInfo API. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, queries]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ResolveOperatorInfoRequest): + request = lva_service.ResolveOperatorInfoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if queries: + request.queries.extend(queries) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.resolve_operator_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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operators(self, + request: Optional[Union[lva_service.ListOperatorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOperatorsAsyncPager: + r"""Lists Operators in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_operators(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListOperatorsRequest, dict]]): + The request object. Message for requesting list of + Operators. + parent (:class:`str`): + Required. Parent value for + ListOperatorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListOperatorsAsyncPager: + Message for response to listing + Operators. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListOperatorsRequest): + request = lva_service.ListOperatorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_operators] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListOperatorsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operator(self, + request: Optional[Union[lva_service.GetOperatorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Operator: + r"""Gets details of a single Operator. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetOperatorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_operator(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetOperatorRequest, dict]]): + The request object. Message for getting a Operator. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Operator: + Message describing the Operator + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetOperatorRequest): + request = lva_service.GetOperatorRequest(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._client._transport._wrapped_methods[self._client._transport.get_operator] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_operator(self, + request: Optional[Union[lva_service.CreateOperatorRequest, dict]] = None, + *, + parent: Optional[str] = None, + operator: Optional[lva_resources.Operator] = None, + operator_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Operator in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateOperatorRequest( + parent="parent_value", + operator_id="operator_id_value", + ) + + # Make the request + operation = client.create_operator(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateOperatorRequest, dict]]): + The request object. Message for creating a Operator. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + operator (:class:`google.cloud.visionai_v1.types.Operator`): + Required. The resource being created. + This corresponds to the ``operator`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + operator_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``operator_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Operator` Message + describing the Operator object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, operator, operator_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateOperatorRequest): + request = lva_service.CreateOperatorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if operator is not None: + request.operator = operator + if operator_id is not None: + request.operator_id = operator_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_operator] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Operator, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_operator(self, + request: Optional[Union[lva_service.UpdateOperatorRequest, dict]] = None, + *, + operator: Optional[lva_resources.Operator] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Operator. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateOperatorRequest( + ) + + # Make the request + operation = client.update_operator(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateOperatorRequest, dict]]): + The request object. Message for updating a Operator. + operator (:class:`google.cloud.visionai_v1.types.Operator`): + Required. The resource being updated + This corresponds to the ``operator`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Operator resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Operator` Message + describing the Operator object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([operator, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateOperatorRequest): + request = lva_service.UpdateOperatorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if operator is not None: + request.operator = operator + 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._client._transport._wrapped_methods[self._client._transport.update_operator] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("operator.name", request.operator.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Operator, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_operator(self, + request: Optional[Union[lva_service.DeleteOperatorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Operator. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteOperatorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_operator(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteOperatorRequest, dict]]): + The request object. Message for deleting a Operator + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteOperatorRequest): + request = lva_service.DeleteOperatorRequest(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._client._transport._wrapped_methods[self._client._transport.delete_operator] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_analyses(self, + request: Optional[Union[lva_service.ListAnalysesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnalysesAsyncPager: + r"""Lists Analyses in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_analyses(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListAnalysesRequest, dict]]): + The request object. Message for requesting list of + Analyses + parent (:class:`str`): + Required. Parent value for + ListAnalysesRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListAnalysesAsyncPager: + Message for response to listing + Analyses + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListAnalysesRequest): + request = lva_service.ListAnalysesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_analyses] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAnalysesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_analysis(self, + request: Optional[Union[lva_service.GetAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Analysis: + r"""Gets details of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = await client.get_analysis(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetAnalysisRequest, dict]]): + The request object. Message for getting an Analysis. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Analysis: + Message describing the Analysis + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetAnalysisRequest): + request = lva_service.GetAnalysisRequest(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._client._transport._wrapped_methods[self._client._transport.get_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_analysis(self, + request: Optional[Union[lva_service.CreateAnalysisRequest, dict]] = None, + *, + parent: Optional[str] = None, + analysis: Optional[lva_resources.Analysis] = None, + analysis_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Analysis in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateAnalysisRequest, dict]]): + The request object. Message for creating an Analysis. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis (:class:`google.cloud.visionai_v1.types.Analysis`): + Required. The resource being created. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``analysis_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Analysis` Message + describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, analysis, analysis_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateAnalysisRequest): + request = lva_service.CreateAnalysisRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if analysis is not None: + request.analysis = analysis + if analysis_id is not None: + request.analysis_id = analysis_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_analysis(self, + request: Optional[Union[lva_service.UpdateAnalysisRequest, dict]] = None, + *, + analysis: Optional[lva_resources.Analysis] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateAnalysisRequest, dict]]): + The request object. Message for updating an Analysis. + analysis (:class:`google.cloud.visionai_v1.types.Analysis`): + Required. The resource being updated. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Analysis resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Analysis` Message + describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([analysis, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateAnalysisRequest): + request = lva_service.UpdateAnalysisRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if analysis is not None: + request.analysis = analysis + 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._client._transport._wrapped_methods[self._client._transport.update_analysis] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis.name", request.analysis.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_analysis(self, + request: Optional[Union[lva_service.DeleteAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteAnalysisRequest, dict]]): + The request object. Message for deleting an Analysis. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteAnalysisRequest): + request = lva_service.DeleteAnalysisRequest(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._client._transport._wrapped_methods[self._client._transport.delete_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_processes(self, + request: Optional[Union[lva_service.ListProcessesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessesAsyncPager: + r"""Lists Processes in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_processes(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListProcessesRequest, dict]]): + The request object. Message for requesting list of + Processes. + parent (:class:`str`): + Required. Parent value for + ListProcessesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListProcessesAsyncPager: + Message for response to listing + Processes. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListProcessesRequest): + request = lva_service.ListProcessesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_processes] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListProcessesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_process(self, + request: Optional[Union[lva_service.GetProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Process: + r"""Gets details of a single Process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessRequest( + name="name_value", + ) + + # Make the request + response = await client.get_process(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetProcessRequest, dict]]): + The request object. Message for getting a Process. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Process: + Message describing the Process + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetProcessRequest): + request = lva_service.GetProcessRequest(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._client._transport._wrapped_methods[self._client._transport.get_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_process(self, + request: Optional[Union[lva_service.CreateProcessRequest, dict]] = None, + *, + parent: Optional[str] = None, + process: Optional[lva_resources.Process] = None, + process_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Process in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.CreateProcessRequest( + parent="parent_value", + process_id="process_id_value", + process=process, + ) + + # Make the request + operation = client.create_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateProcessRequest, dict]]): + The request object. Message for creating a Process. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + process (:class:`google.cloud.visionai_v1.types.Process`): + Required. The resource being created. + This corresponds to the ``process`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + process_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``process_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Process` Message + describing the Process object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, process, process_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateProcessRequest): + request = lva_service.CreateProcessRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if process is not None: + request.process = process + if process_id is not None: + request.process_id = process_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Process, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_process(self, + request: Optional[Union[lva_service.UpdateProcessRequest, dict]] = None, + *, + process: Optional[lva_resources.Process] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.UpdateProcessRequest( + process=process, + ) + + # Make the request + operation = client.update_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateProcessRequest, dict]]): + The request object. Message for updating a Process. + process (:class:`google.cloud.visionai_v1.types.Process`): + Required. The resource being updated. + This corresponds to the ``process`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Process resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Process` Message + describing the Process object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([process, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateProcessRequest): + request = lva_service.UpdateProcessRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if process is not None: + request.process = process + 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._client._transport._wrapped_methods[self._client._transport.update_process] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("process.name", request.process.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Process, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_process(self, + request: Optional[Union[lva_service.DeleteProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteProcessRequest, dict]]): + The request object. Message for deleting a Process. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteProcessRequest): + request = lva_service.DeleteProcessRequest(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._client._transport._wrapped_methods[self._client._transport.delete_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def batch_run_process(self, + request: Optional[Union[lva_service.BatchRunProcessRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[lva_service.CreateProcessRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Run all of the processes to "completion". Max time + for each process is the LRO time limit. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_batch_run_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + requests = visionai_v1.CreateProcessRequest() + requests.parent = "parent_value" + requests.process_id = "process_id_value" + requests.process.analysis = "analysis_value" + + request = visionai_v1.BatchRunProcessRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_run_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.BatchRunProcessRequest, dict]]): + The request object. Request message for running the + processes in a batch. + parent (:class:`str`): + Required. The parent resource shared + by all processes being created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (:class:`MutableSequence[google.cloud.visionai_v1.types.CreateProcessRequest]`): + Required. The create process + requests. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.BatchRunProcessResponse` + Response message for running the processes in a batch. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.BatchRunProcessRequest): + request = lva_service.BatchRunProcessRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests: + request.requests.extend(requests) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_run_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_service.BatchRunProcessResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "LiveVideoAnalyticsAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "LiveVideoAnalyticsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/client.py new file mode 100644 index 000000000000..3463a8290cd4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/client.py @@ -0,0 +1,3022 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.live_video_analytics import pagers +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import lva +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LiveVideoAnalyticsGrpcTransport +from .transports.grpc_asyncio import LiveVideoAnalyticsGrpcAsyncIOTransport +from .transports.rest import LiveVideoAnalyticsRestTransport + + +class LiveVideoAnalyticsClientMeta(type): + """Metaclass for the LiveVideoAnalytics 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[LiveVideoAnalyticsTransport]] + _transport_registry["grpc"] = LiveVideoAnalyticsGrpcTransport + _transport_registry["grpc_asyncio"] = LiveVideoAnalyticsGrpcAsyncIOTransport + _transport_registry["rest"] = LiveVideoAnalyticsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LiveVideoAnalyticsTransport]: + """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 LiveVideoAnalyticsClient(metaclass=LiveVideoAnalyticsClientMeta): + """Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + LiveVideoAnalyticsClient: 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: + LiveVideoAnalyticsClient: 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) -> LiveVideoAnalyticsTransport: + """Returns the transport used by the client instance. + + Returns: + LiveVideoAnalyticsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def analysis_path(project: str,location: str,cluster: str,analysis: str,) -> str: + """Returns a fully-qualified analysis string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/analyses/{analysis}".format(project=project, location=location, cluster=cluster, analysis=analysis, ) + + @staticmethod + def parse_analysis_path(path: str) -> Dict[str,str]: + """Parses a analysis path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/analyses/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def operator_path(project: str,location: str,operator: str,) -> str: + """Returns a fully-qualified operator string.""" + return "projects/{project}/locations/{location}/operators/{operator}".format(project=project, location=location, operator=operator, ) + + @staticmethod + def parse_operator_path(path: str) -> Dict[str,str]: + """Parses a operator path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/operators/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def process_path(project: str,location: str,cluster: str,process: str,) -> str: + """Returns a fully-qualified process string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/processes/{process}".format(project=project, location=location, cluster=cluster, process=process, ) + + @staticmethod + def parse_process_path(path: str) -> Dict[str,str]: + """Parses a process path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/processes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + LiveVideoAnalyticsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LiveVideoAnalyticsTransport, Callable[..., LiveVideoAnalyticsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the live video analytics 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 (Optional[Union[str,LiveVideoAnalyticsTransport,Callable[..., LiveVideoAnalyticsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LiveVideoAnalyticsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LiveVideoAnalyticsClient._read_environment_variables() + self._client_cert_source = LiveVideoAnalyticsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LiveVideoAnalyticsClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, LiveVideoAnalyticsTransport) + if transport_provided: + # transport is a LiveVideoAnalyticsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(LiveVideoAnalyticsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LiveVideoAnalyticsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[LiveVideoAnalyticsTransport], Callable[..., LiveVideoAnalyticsTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LiveVideoAnalyticsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_public_operators(self, + request: Optional[Union[lva_service.ListPublicOperatorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPublicOperatorsPager: + r"""ListPublicOperators returns all the operators in + public registry. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_public_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListPublicOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_public_operators(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListPublicOperatorsRequest, dict]): + The request object. Request message of + ListPublicOperatorsRequest API. + parent (str): + Required. Parent value for + ListPublicOperatorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListPublicOperatorsPager: + Response message of + ListPublicOperators API. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListPublicOperatorsRequest): + request = lva_service.ListPublicOperatorsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_public_operators] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListPublicOperatorsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def resolve_operator_info(self, + request: Optional[Union[lva_service.ResolveOperatorInfoRequest, dict]] = None, + *, + parent: Optional[str] = None, + queries: Optional[MutableSequence[lva_service.OperatorQuery]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_service.ResolveOperatorInfoResponse: + r"""ResolveOperatorInfo returns the operator information + based on the request. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_resolve_operator_info(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + queries = visionai_v1.OperatorQuery() + queries.operator = "operator_value" + + request = visionai_v1.ResolveOperatorInfoRequest( + parent="parent_value", + queries=queries, + ) + + # Make the request + response = client.resolve_operator_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ResolveOperatorInfoRequest, dict]): + The request object. Request message for querying operator + info. + parent (str): + Required. Parent value for + ResolveOperatorInfoRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + queries (MutableSequence[google.cloud.visionai_v1.types.OperatorQuery]): + Required. The operator queries. + This corresponds to the ``queries`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ResolveOperatorInfoResponse: + Response message of + ResolveOperatorInfo API. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, queries]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ResolveOperatorInfoRequest): + request = lva_service.ResolveOperatorInfoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if queries is not None: + request.queries = queries + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resolve_operator_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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_operators(self, + request: Optional[Union[lva_service.ListOperatorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOperatorsPager: + r"""Lists Operators in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_operators(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListOperatorsRequest, dict]): + The request object. Message for requesting list of + Operators. + parent (str): + Required. Parent value for + ListOperatorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListOperatorsPager: + Message for response to listing + Operators. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListOperatorsRequest): + request = lva_service.ListOperatorsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operators] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListOperatorsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operator(self, + request: Optional[Union[lva_service.GetOperatorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Operator: + r"""Gets details of a single Operator. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.GetOperatorRequest( + name="name_value", + ) + + # Make the request + response = client.get_operator(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetOperatorRequest, dict]): + The request object. Message for getting a Operator. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Operator: + Message describing the Operator + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetOperatorRequest): + request = lva_service.GetOperatorRequest(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_operator] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_operator(self, + request: Optional[Union[lva_service.CreateOperatorRequest, dict]] = None, + *, + parent: Optional[str] = None, + operator: Optional[lva_resources.Operator] = None, + operator_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Operator in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.CreateOperatorRequest( + parent="parent_value", + operator_id="operator_id_value", + ) + + # Make the request + operation = client.create_operator(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateOperatorRequest, dict]): + The request object. Message for creating a Operator. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + operator (google.cloud.visionai_v1.types.Operator): + Required. The resource being created. + This corresponds to the ``operator`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + operator_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``operator_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Operator` Message + describing the Operator object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, operator, operator_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateOperatorRequest): + request = lva_service.CreateOperatorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if operator is not None: + request.operator = operator + if operator_id is not None: + request.operator_id = operator_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_operator] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Operator, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_operator(self, + request: Optional[Union[lva_service.UpdateOperatorRequest, dict]] = None, + *, + operator: Optional[lva_resources.Operator] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Operator. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateOperatorRequest( + ) + + # Make the request + operation = client.update_operator(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateOperatorRequest, dict]): + The request object. Message for updating a Operator. + operator (google.cloud.visionai_v1.types.Operator): + Required. The resource being updated + This corresponds to the ``operator`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Operator resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Operator` Message + describing the Operator object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([operator, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateOperatorRequest): + request = lva_service.UpdateOperatorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if operator is not None: + request.operator = operator + 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_operator] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("operator.name", request.operator.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Operator, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_operator(self, + request: Optional[Union[lva_service.DeleteOperatorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Operator. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteOperatorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_operator(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteOperatorRequest, dict]): + The request object. Message for deleting a Operator + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteOperatorRequest): + request = lva_service.DeleteOperatorRequest(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_operator] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_analyses(self, + request: Optional[Union[lva_service.ListAnalysesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnalysesPager: + r"""Lists Analyses in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_analyses(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListAnalysesRequest, dict]): + The request object. Message for requesting list of + Analyses + parent (str): + Required. Parent value for + ListAnalysesRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListAnalysesPager: + Message for response to listing + Analyses + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListAnalysesRequest): + request = lva_service.ListAnalysesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_analyses] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAnalysesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_analysis(self, + request: Optional[Union[lva_service.GetAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Analysis: + r"""Gets details of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = client.get_analysis(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetAnalysisRequest, dict]): + The request object. Message for getting an Analysis. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Analysis: + Message describing the Analysis + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetAnalysisRequest): + request = lva_service.GetAnalysisRequest(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_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_analysis(self, + request: Optional[Union[lva_service.CreateAnalysisRequest, dict]] = None, + *, + parent: Optional[str] = None, + analysis: Optional[lva_resources.Analysis] = None, + analysis_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Analysis in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateAnalysisRequest, dict]): + The request object. Message for creating an Analysis. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis (google.cloud.visionai_v1.types.Analysis): + Required. The resource being created. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``analysis_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Analysis` Message + describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, analysis, analysis_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateAnalysisRequest): + request = lva_service.CreateAnalysisRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if analysis is not None: + request.analysis = analysis + if analysis_id is not None: + request.analysis_id = analysis_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_analysis(self, + request: Optional[Union[lva_service.UpdateAnalysisRequest, dict]] = None, + *, + analysis: Optional[lva_resources.Analysis] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateAnalysisRequest, dict]): + The request object. Message for updating an Analysis. + analysis (google.cloud.visionai_v1.types.Analysis): + Required. The resource being updated. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Analysis resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Analysis` Message + describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([analysis, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateAnalysisRequest): + request = lva_service.UpdateAnalysisRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if analysis is not None: + request.analysis = analysis + 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_analysis] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis.name", request.analysis.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_analysis(self, + request: Optional[Union[lva_service.DeleteAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteAnalysisRequest, dict]): + The request object. Message for deleting an Analysis. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteAnalysisRequest): + request = lva_service.DeleteAnalysisRequest(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_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_processes(self, + request: Optional[Union[lva_service.ListProcessesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessesPager: + r"""Lists Processes in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_processes(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListProcessesRequest, dict]): + The request object. Message for requesting list of + Processes. + parent (str): + Required. Parent value for + ListProcessesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.live_video_analytics.pagers.ListProcessesPager: + Message for response to listing + Processes. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListProcessesRequest): + request = lva_service.ListProcessesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_processes] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListProcessesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_process(self, + request: Optional[Union[lva_service.GetProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Process: + r"""Gets details of a single Process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessRequest( + name="name_value", + ) + + # Make the request + response = client.get_process(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetProcessRequest, dict]): + The request object. Message for getting a Process. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Process: + Message describing the Process + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetProcessRequest): + request = lva_service.GetProcessRequest(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_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_process(self, + request: Optional[Union[lva_service.CreateProcessRequest, dict]] = None, + *, + parent: Optional[str] = None, + process: Optional[lva_resources.Process] = None, + process_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Process in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.CreateProcessRequest( + parent="parent_value", + process_id="process_id_value", + process=process, + ) + + # Make the request + operation = client.create_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateProcessRequest, dict]): + The request object. Message for creating a Process. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + process (google.cloud.visionai_v1.types.Process): + Required. The resource being created. + This corresponds to the ``process`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + process_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``process_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Process` Message + describing the Process object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, process, process_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateProcessRequest): + request = lva_service.CreateProcessRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if process is not None: + request.process = process + if process_id is not None: + request.process_id = process_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Process, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_process(self, + request: Optional[Union[lva_service.UpdateProcessRequest, dict]] = None, + *, + process: Optional[lva_resources.Process] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.UpdateProcessRequest( + process=process, + ) + + # Make the request + operation = client.update_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateProcessRequest, dict]): + The request object. Message for updating a Process. + process (google.cloud.visionai_v1.types.Process): + Required. The resource being updated. + This corresponds to the ``process`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Process resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Process` Message + describing the Process object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([process, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateProcessRequest): + request = lva_service.UpdateProcessRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if process is not None: + request.process = process + 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_process] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("process.name", request.process.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Process, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_process(self, + request: Optional[Union[lva_service.DeleteProcessRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteProcessRequest, dict]): + The request object. Message for deleting a Process. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteProcessRequest): + request = lva_service.DeleteProcessRequest(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_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def batch_run_process(self, + request: Optional[Union[lva_service.BatchRunProcessRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[lva_service.CreateProcessRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Run all of the processes to "completion". Max time + for each process is the LRO time limit. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_batch_run_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + requests = visionai_v1.CreateProcessRequest() + requests.parent = "parent_value" + requests.process_id = "process_id_value" + requests.process.analysis = "analysis_value" + + request = visionai_v1.BatchRunProcessRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_run_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.BatchRunProcessRequest, dict]): + The request object. Request message for running the + processes in a batch. + parent (str): + Required. The parent resource shared + by all processes being created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.cloud.visionai_v1.types.CreateProcessRequest]): + Required. The create process + requests. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.BatchRunProcessResponse` + Response message for running the processes in a batch. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.BatchRunProcessRequest): + request = lva_service.BatchRunProcessRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_run_process] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_service.BatchRunProcessResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LiveVideoAnalyticsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "LiveVideoAnalyticsClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/pagers.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/pagers.py new file mode 100644 index 000000000000..209ffb259e1d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/pagers.py @@ -0,0 +1,503 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service + + +class ListPublicOperatorsPager: + """A pager for iterating through ``list_public_operators`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListPublicOperatorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``operators`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPublicOperators`` requests and continue to iterate + through the ``operators`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListPublicOperatorsResponse` + 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[..., lva_service.ListPublicOperatorsResponse], + request: lva_service.ListPublicOperatorsRequest, + response: lva_service.ListPublicOperatorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListPublicOperatorsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListPublicOperatorsResponse): + 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 = lva_service.ListPublicOperatorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[lva_service.ListPublicOperatorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[lva_resources.Operator]: + for page in self.pages: + yield from page.operators + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPublicOperatorsAsyncPager: + """A pager for iterating through ``list_public_operators`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListPublicOperatorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``operators`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPublicOperators`` requests and continue to iterate + through the ``operators`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListPublicOperatorsResponse` + 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[lva_service.ListPublicOperatorsResponse]], + request: lva_service.ListPublicOperatorsRequest, + response: lva_service.ListPublicOperatorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListPublicOperatorsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListPublicOperatorsResponse): + 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 = lva_service.ListPublicOperatorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[lva_service.ListPublicOperatorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[lva_resources.Operator]: + async def async_generator(): + async for page in self.pages: + for response in page.operators: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOperatorsPager: + """A pager for iterating through ``list_operators`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListOperatorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``operators`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOperators`` requests and continue to iterate + through the ``operators`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListOperatorsResponse` + 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[..., lva_service.ListOperatorsResponse], + request: lva_service.ListOperatorsRequest, + response: lva_service.ListOperatorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListOperatorsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListOperatorsResponse): + 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 = lva_service.ListOperatorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[lva_service.ListOperatorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[lva_resources.Operator]: + for page in self.pages: + yield from page.operators + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOperatorsAsyncPager: + """A pager for iterating through ``list_operators`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListOperatorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``operators`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOperators`` requests and continue to iterate + through the ``operators`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListOperatorsResponse` + 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[lva_service.ListOperatorsResponse]], + request: lva_service.ListOperatorsRequest, + response: lva_service.ListOperatorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListOperatorsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListOperatorsResponse): + 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 = lva_service.ListOperatorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[lva_service.ListOperatorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[lva_resources.Operator]: + async def async_generator(): + async for page in self.pages: + for response in page.operators: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnalysesPager: + """A pager for iterating through ``list_analyses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListAnalysesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``analyses`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnalyses`` requests and continue to iterate + through the ``analyses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListAnalysesResponse` + 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[..., lva_service.ListAnalysesResponse], + request: lva_service.ListAnalysesRequest, + response: lva_service.ListAnalysesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListAnalysesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListAnalysesResponse): + 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 = lva_service.ListAnalysesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[lva_service.ListAnalysesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[lva_resources.Analysis]: + for page in self.pages: + yield from page.analyses + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnalysesAsyncPager: + """A pager for iterating through ``list_analyses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListAnalysesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``analyses`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnalyses`` requests and continue to iterate + through the ``analyses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListAnalysesResponse` + 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[lva_service.ListAnalysesResponse]], + request: lva_service.ListAnalysesRequest, + response: lva_service.ListAnalysesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListAnalysesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListAnalysesResponse): + 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 = lva_service.ListAnalysesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[lva_service.ListAnalysesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[lva_resources.Analysis]: + async def async_generator(): + async for page in self.pages: + for response in page.analyses: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessesPager: + """A pager for iterating through ``list_processes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListProcessesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcesses`` requests and continue to iterate + through the ``processes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListProcessesResponse` + 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[..., lva_service.ListProcessesResponse], + request: lva_service.ListProcessesRequest, + response: lva_service.ListProcessesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListProcessesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListProcessesResponse): + 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 = lva_service.ListProcessesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[lva_service.ListProcessesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[lva_resources.Process]: + for page in self.pages: + yield from page.processes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessesAsyncPager: + """A pager for iterating through ``list_processes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListProcessesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcesses`` requests and continue to iterate + through the ``processes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListProcessesResponse` + 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[lva_service.ListProcessesResponse]], + request: lva_service.ListProcessesRequest, + response: lva_service.ListProcessesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListProcessesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListProcessesResponse): + 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 = lva_service.ListProcessesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[lva_service.ListProcessesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[lva_resources.Process]: + async def async_generator(): + async for page in self.pages: + for response in page.processes: + 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/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/__init__.py new file mode 100644 index 000000000000..3d5c836f709a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LiveVideoAnalyticsTransport +from .grpc import LiveVideoAnalyticsGrpcTransport +from .grpc_asyncio import LiveVideoAnalyticsGrpcAsyncIOTransport +from .rest import LiveVideoAnalyticsRestTransport +from .rest import LiveVideoAnalyticsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LiveVideoAnalyticsTransport]] +_transport_registry['grpc'] = LiveVideoAnalyticsGrpcTransport +_transport_registry['grpc_asyncio'] = LiveVideoAnalyticsGrpcAsyncIOTransport +_transport_registry['rest'] = LiveVideoAnalyticsRestTransport + +__all__ = ( + 'LiveVideoAnalyticsTransport', + 'LiveVideoAnalyticsGrpcTransport', + 'LiveVideoAnalyticsGrpcAsyncIOTransport', + 'LiveVideoAnalyticsRestTransport', + 'LiveVideoAnalyticsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/base.py new file mode 100644 index 000000000000..5bcf246912fe --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/base.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class LiveVideoAnalyticsTransport(abc.ABC): + """Abstract transport class for LiveVideoAnalytics.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_public_operators: gapic_v1.method.wrap_method( + self.list_public_operators, + default_timeout=None, + client_info=client_info, + ), + self.resolve_operator_info: gapic_v1.method.wrap_method( + self.resolve_operator_info, + default_timeout=None, + client_info=client_info, + ), + self.list_operators: gapic_v1.method.wrap_method( + self.list_operators, + default_timeout=60.0, + client_info=client_info, + ), + self.get_operator: gapic_v1.method.wrap_method( + self.get_operator, + default_timeout=60.0, + client_info=client_info, + ), + self.create_operator: gapic_v1.method.wrap_method( + self.create_operator, + default_timeout=300.0, + client_info=client_info, + ), + self.update_operator: gapic_v1.method.wrap_method( + self.update_operator, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_operator: gapic_v1.method.wrap_method( + self.delete_operator, + default_timeout=60.0, + client_info=client_info, + ), + self.list_analyses: gapic_v1.method.wrap_method( + self.list_analyses, + default_timeout=60.0, + client_info=client_info, + ), + self.get_analysis: gapic_v1.method.wrap_method( + self.get_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.create_analysis: gapic_v1.method.wrap_method( + self.create_analysis, + default_timeout=300.0, + client_info=client_info, + ), + self.update_analysis: gapic_v1.method.wrap_method( + self.update_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_analysis: gapic_v1.method.wrap_method( + self.delete_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.list_processes: gapic_v1.method.wrap_method( + self.list_processes, + default_timeout=None, + client_info=client_info, + ), + self.get_process: gapic_v1.method.wrap_method( + self.get_process, + default_timeout=None, + client_info=client_info, + ), + self.create_process: gapic_v1.method.wrap_method( + self.create_process, + default_timeout=None, + client_info=client_info, + ), + self.update_process: gapic_v1.method.wrap_method( + self.update_process, + default_timeout=None, + client_info=client_info, + ), + self.delete_process: gapic_v1.method.wrap_method( + self.delete_process, + default_timeout=None, + client_info=client_info, + ), + self.batch_run_process: gapic_v1.method.wrap_method( + self.batch_run_process, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_public_operators(self) -> Callable[ + [lva_service.ListPublicOperatorsRequest], + Union[ + lva_service.ListPublicOperatorsResponse, + Awaitable[lva_service.ListPublicOperatorsResponse] + ]]: + raise NotImplementedError() + + @property + def resolve_operator_info(self) -> Callable[ + [lva_service.ResolveOperatorInfoRequest], + Union[ + lva_service.ResolveOperatorInfoResponse, + Awaitable[lva_service.ResolveOperatorInfoResponse] + ]]: + raise NotImplementedError() + + @property + def list_operators(self) -> Callable[ + [lva_service.ListOperatorsRequest], + Union[ + lva_service.ListOperatorsResponse, + Awaitable[lva_service.ListOperatorsResponse] + ]]: + raise NotImplementedError() + + @property + def get_operator(self) -> Callable[ + [lva_service.GetOperatorRequest], + Union[ + lva_resources.Operator, + Awaitable[lva_resources.Operator] + ]]: + raise NotImplementedError() + + @property + def create_operator(self) -> Callable[ + [lva_service.CreateOperatorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_operator(self) -> Callable[ + [lva_service.UpdateOperatorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_operator(self) -> Callable[ + [lva_service.DeleteOperatorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + Union[ + lva_service.ListAnalysesResponse, + Awaitable[lva_service.ListAnalysesResponse] + ]]: + raise NotImplementedError() + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + Union[ + lva_resources.Analysis, + Awaitable[lva_resources.Analysis] + ]]: + raise NotImplementedError() + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_processes(self) -> Callable[ + [lva_service.ListProcessesRequest], + Union[ + lva_service.ListProcessesResponse, + Awaitable[lva_service.ListProcessesResponse] + ]]: + raise NotImplementedError() + + @property + def get_process(self) -> Callable[ + [lva_service.GetProcessRequest], + Union[ + lva_resources.Process, + Awaitable[lva_resources.Process] + ]]: + raise NotImplementedError() + + @property + def create_process(self) -> Callable[ + [lva_service.CreateProcessRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_process(self) -> Callable[ + [lva_service.UpdateProcessRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_process(self) -> Callable[ + [lva_service.DeleteProcessRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_run_process(self) -> Callable[ + [lva_service.BatchRunProcessRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LiveVideoAnalyticsTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/grpc.py new file mode 100644 index 000000000000..ee9bd34d88c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/grpc.py @@ -0,0 +1,814 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO + + +class LiveVideoAnalyticsGrpcTransport(LiveVideoAnalyticsTransport): + """gRPC backend transport for LiveVideoAnalytics. + + Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_public_operators(self) -> Callable[ + [lva_service.ListPublicOperatorsRequest], + lva_service.ListPublicOperatorsResponse]: + r"""Return a callable for the list public operators method over gRPC. + + ListPublicOperators returns all the operators in + public registry. + + Returns: + Callable[[~.ListPublicOperatorsRequest], + ~.ListPublicOperatorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_public_operators' not in self._stubs: + self._stubs['list_public_operators'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListPublicOperators', + request_serializer=lva_service.ListPublicOperatorsRequest.serialize, + response_deserializer=lva_service.ListPublicOperatorsResponse.deserialize, + ) + return self._stubs['list_public_operators'] + + @property + def resolve_operator_info(self) -> Callable[ + [lva_service.ResolveOperatorInfoRequest], + lva_service.ResolveOperatorInfoResponse]: + r"""Return a callable for the resolve operator info method over gRPC. + + ResolveOperatorInfo returns the operator information + based on the request. + + Returns: + Callable[[~.ResolveOperatorInfoRequest], + ~.ResolveOperatorInfoResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resolve_operator_info' not in self._stubs: + self._stubs['resolve_operator_info'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ResolveOperatorInfo', + request_serializer=lva_service.ResolveOperatorInfoRequest.serialize, + response_deserializer=lva_service.ResolveOperatorInfoResponse.deserialize, + ) + return self._stubs['resolve_operator_info'] + + @property + def list_operators(self) -> Callable[ + [lva_service.ListOperatorsRequest], + lva_service.ListOperatorsResponse]: + r"""Return a callable for the list operators method over gRPC. + + Lists Operators in a given project and location. + + Returns: + Callable[[~.ListOperatorsRequest], + ~.ListOperatorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_operators' not in self._stubs: + self._stubs['list_operators'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListOperators', + request_serializer=lva_service.ListOperatorsRequest.serialize, + response_deserializer=lva_service.ListOperatorsResponse.deserialize, + ) + return self._stubs['list_operators'] + + @property + def get_operator(self) -> Callable[ + [lva_service.GetOperatorRequest], + lva_resources.Operator]: + r"""Return a callable for the get operator method over gRPC. + + Gets details of a single Operator. + + Returns: + Callable[[~.GetOperatorRequest], + ~.Operator]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_operator' not in self._stubs: + self._stubs['get_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/GetOperator', + request_serializer=lva_service.GetOperatorRequest.serialize, + response_deserializer=lva_resources.Operator.deserialize, + ) + return self._stubs['get_operator'] + + @property + def create_operator(self) -> Callable[ + [lva_service.CreateOperatorRequest], + operations_pb2.Operation]: + r"""Return a callable for the create operator method over gRPC. + + Creates a new Operator in a given project and + location. + + Returns: + Callable[[~.CreateOperatorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_operator' not in self._stubs: + self._stubs['create_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/CreateOperator', + request_serializer=lva_service.CreateOperatorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_operator'] + + @property + def update_operator(self) -> Callable[ + [lva_service.UpdateOperatorRequest], + operations_pb2.Operation]: + r"""Return a callable for the update operator method over gRPC. + + Updates the parameters of a single Operator. + + Returns: + Callable[[~.UpdateOperatorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_operator' not in self._stubs: + self._stubs['update_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/UpdateOperator', + request_serializer=lva_service.UpdateOperatorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_operator'] + + @property + def delete_operator(self) -> Callable[ + [lva_service.DeleteOperatorRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete operator method over gRPC. + + Deletes a single Operator. + + Returns: + Callable[[~.DeleteOperatorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_operator' not in self._stubs: + self._stubs['delete_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/DeleteOperator', + request_serializer=lva_service.DeleteOperatorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_operator'] + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + lva_service.ListAnalysesResponse]: + r"""Return a callable for the list analyses method over gRPC. + + Lists Analyses in a given project and location. + + Returns: + Callable[[~.ListAnalysesRequest], + ~.ListAnalysesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analyses' not in self._stubs: + self._stubs['list_analyses'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListAnalyses', + request_serializer=lva_service.ListAnalysesRequest.serialize, + response_deserializer=lva_service.ListAnalysesResponse.deserialize, + ) + return self._stubs['list_analyses'] + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + lva_resources.Analysis]: + r"""Return a callable for the get analysis method over gRPC. + + Gets details of a single Analysis. + + Returns: + Callable[[~.GetAnalysisRequest], + ~.Analysis]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analysis' not in self._stubs: + self._stubs['get_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/GetAnalysis', + request_serializer=lva_service.GetAnalysisRequest.serialize, + response_deserializer=lva_resources.Analysis.deserialize, + ) + return self._stubs['get_analysis'] + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + operations_pb2.Operation]: + r"""Return a callable for the create analysis method over gRPC. + + Creates a new Analysis in a given project and + location. + + Returns: + Callable[[~.CreateAnalysisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_analysis' not in self._stubs: + self._stubs['create_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/CreateAnalysis', + request_serializer=lva_service.CreateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_analysis'] + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + operations_pb2.Operation]: + r"""Return a callable for the update analysis method over gRPC. + + Updates the parameters of a single Analysis. + + Returns: + Callable[[~.UpdateAnalysisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_analysis' not in self._stubs: + self._stubs['update_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/UpdateAnalysis', + request_serializer=lva_service.UpdateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_analysis'] + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete analysis method over gRPC. + + Deletes a single Analysis. + + Returns: + Callable[[~.DeleteAnalysisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_analysis' not in self._stubs: + self._stubs['delete_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/DeleteAnalysis', + request_serializer=lva_service.DeleteAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_analysis'] + + @property + def list_processes(self) -> Callable[ + [lva_service.ListProcessesRequest], + lva_service.ListProcessesResponse]: + r"""Return a callable for the list processes method over gRPC. + + Lists Processes in a given project and location. + + Returns: + Callable[[~.ListProcessesRequest], + ~.ListProcessesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processes' not in self._stubs: + self._stubs['list_processes'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListProcesses', + request_serializer=lva_service.ListProcessesRequest.serialize, + response_deserializer=lva_service.ListProcessesResponse.deserialize, + ) + return self._stubs['list_processes'] + + @property + def get_process(self) -> Callable[ + [lva_service.GetProcessRequest], + lva_resources.Process]: + r"""Return a callable for the get process method over gRPC. + + Gets details of a single Process. + + Returns: + Callable[[~.GetProcessRequest], + ~.Process]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_process' not in self._stubs: + self._stubs['get_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/GetProcess', + request_serializer=lva_service.GetProcessRequest.serialize, + response_deserializer=lva_resources.Process.deserialize, + ) + return self._stubs['get_process'] + + @property + def create_process(self) -> Callable[ + [lva_service.CreateProcessRequest], + operations_pb2.Operation]: + r"""Return a callable for the create process method over gRPC. + + Creates a new Process in a given project and + location. + + Returns: + Callable[[~.CreateProcessRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_process' not in self._stubs: + self._stubs['create_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/CreateProcess', + request_serializer=lva_service.CreateProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_process'] + + @property + def update_process(self) -> Callable[ + [lva_service.UpdateProcessRequest], + operations_pb2.Operation]: + r"""Return a callable for the update process method over gRPC. + + Updates the parameters of a single Process. + + Returns: + Callable[[~.UpdateProcessRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_process' not in self._stubs: + self._stubs['update_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/UpdateProcess', + request_serializer=lva_service.UpdateProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_process'] + + @property + def delete_process(self) -> Callable[ + [lva_service.DeleteProcessRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete process method over gRPC. + + Deletes a single Process. + + Returns: + Callable[[~.DeleteProcessRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_process' not in self._stubs: + self._stubs['delete_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/DeleteProcess', + request_serializer=lva_service.DeleteProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_process'] + + @property + def batch_run_process(self) -> Callable[ + [lva_service.BatchRunProcessRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch run process method over gRPC. + + Run all of the processes to "completion". Max time + for each process is the LRO time limit. + + Returns: + Callable[[~.BatchRunProcessRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_process' not in self._stubs: + self._stubs['batch_run_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/BatchRunProcess', + request_serializer=lva_service.BatchRunProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_process'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LiveVideoAnalyticsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ee3152edde63 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/grpc_asyncio.py @@ -0,0 +1,909 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO +from .grpc import LiveVideoAnalyticsGrpcTransport + + +class LiveVideoAnalyticsGrpcAsyncIOTransport(LiveVideoAnalyticsTransport): + """gRPC AsyncIO backend transport for LiveVideoAnalytics. + + Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_public_operators(self) -> Callable[ + [lva_service.ListPublicOperatorsRequest], + Awaitable[lva_service.ListPublicOperatorsResponse]]: + r"""Return a callable for the list public operators method over gRPC. + + ListPublicOperators returns all the operators in + public registry. + + Returns: + Callable[[~.ListPublicOperatorsRequest], + Awaitable[~.ListPublicOperatorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_public_operators' not in self._stubs: + self._stubs['list_public_operators'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListPublicOperators', + request_serializer=lva_service.ListPublicOperatorsRequest.serialize, + response_deserializer=lva_service.ListPublicOperatorsResponse.deserialize, + ) + return self._stubs['list_public_operators'] + + @property + def resolve_operator_info(self) -> Callable[ + [lva_service.ResolveOperatorInfoRequest], + Awaitable[lva_service.ResolveOperatorInfoResponse]]: + r"""Return a callable for the resolve operator info method over gRPC. + + ResolveOperatorInfo returns the operator information + based on the request. + + Returns: + Callable[[~.ResolveOperatorInfoRequest], + Awaitable[~.ResolveOperatorInfoResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resolve_operator_info' not in self._stubs: + self._stubs['resolve_operator_info'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ResolveOperatorInfo', + request_serializer=lva_service.ResolveOperatorInfoRequest.serialize, + response_deserializer=lva_service.ResolveOperatorInfoResponse.deserialize, + ) + return self._stubs['resolve_operator_info'] + + @property + def list_operators(self) -> Callable[ + [lva_service.ListOperatorsRequest], + Awaitable[lva_service.ListOperatorsResponse]]: + r"""Return a callable for the list operators method over gRPC. + + Lists Operators in a given project and location. + + Returns: + Callable[[~.ListOperatorsRequest], + Awaitable[~.ListOperatorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_operators' not in self._stubs: + self._stubs['list_operators'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListOperators', + request_serializer=lva_service.ListOperatorsRequest.serialize, + response_deserializer=lva_service.ListOperatorsResponse.deserialize, + ) + return self._stubs['list_operators'] + + @property + def get_operator(self) -> Callable[ + [lva_service.GetOperatorRequest], + Awaitable[lva_resources.Operator]]: + r"""Return a callable for the get operator method over gRPC. + + Gets details of a single Operator. + + Returns: + Callable[[~.GetOperatorRequest], + Awaitable[~.Operator]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_operator' not in self._stubs: + self._stubs['get_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/GetOperator', + request_serializer=lva_service.GetOperatorRequest.serialize, + response_deserializer=lva_resources.Operator.deserialize, + ) + return self._stubs['get_operator'] + + @property + def create_operator(self) -> Callable[ + [lva_service.CreateOperatorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create operator method over gRPC. + + Creates a new Operator in a given project and + location. + + Returns: + Callable[[~.CreateOperatorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_operator' not in self._stubs: + self._stubs['create_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/CreateOperator', + request_serializer=lva_service.CreateOperatorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_operator'] + + @property + def update_operator(self) -> Callable[ + [lva_service.UpdateOperatorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update operator method over gRPC. + + Updates the parameters of a single Operator. + + Returns: + Callable[[~.UpdateOperatorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_operator' not in self._stubs: + self._stubs['update_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/UpdateOperator', + request_serializer=lva_service.UpdateOperatorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_operator'] + + @property + def delete_operator(self) -> Callable[ + [lva_service.DeleteOperatorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete operator method over gRPC. + + Deletes a single Operator. + + Returns: + Callable[[~.DeleteOperatorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_operator' not in self._stubs: + self._stubs['delete_operator'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/DeleteOperator', + request_serializer=lva_service.DeleteOperatorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_operator'] + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + Awaitable[lva_service.ListAnalysesResponse]]: + r"""Return a callable for the list analyses method over gRPC. + + Lists Analyses in a given project and location. + + Returns: + Callable[[~.ListAnalysesRequest], + Awaitable[~.ListAnalysesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analyses' not in self._stubs: + self._stubs['list_analyses'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListAnalyses', + request_serializer=lva_service.ListAnalysesRequest.serialize, + response_deserializer=lva_service.ListAnalysesResponse.deserialize, + ) + return self._stubs['list_analyses'] + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + Awaitable[lva_resources.Analysis]]: + r"""Return a callable for the get analysis method over gRPC. + + Gets details of a single Analysis. + + Returns: + Callable[[~.GetAnalysisRequest], + Awaitable[~.Analysis]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analysis' not in self._stubs: + self._stubs['get_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/GetAnalysis', + request_serializer=lva_service.GetAnalysisRequest.serialize, + response_deserializer=lva_resources.Analysis.deserialize, + ) + return self._stubs['get_analysis'] + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create analysis method over gRPC. + + Creates a new Analysis in a given project and + location. + + Returns: + Callable[[~.CreateAnalysisRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_analysis' not in self._stubs: + self._stubs['create_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/CreateAnalysis', + request_serializer=lva_service.CreateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_analysis'] + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update analysis method over gRPC. + + Updates the parameters of a single Analysis. + + Returns: + Callable[[~.UpdateAnalysisRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_analysis' not in self._stubs: + self._stubs['update_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/UpdateAnalysis', + request_serializer=lva_service.UpdateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_analysis'] + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete analysis method over gRPC. + + Deletes a single Analysis. + + Returns: + Callable[[~.DeleteAnalysisRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_analysis' not in self._stubs: + self._stubs['delete_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/DeleteAnalysis', + request_serializer=lva_service.DeleteAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_analysis'] + + @property + def list_processes(self) -> Callable[ + [lva_service.ListProcessesRequest], + Awaitable[lva_service.ListProcessesResponse]]: + r"""Return a callable for the list processes method over gRPC. + + Lists Processes in a given project and location. + + Returns: + Callable[[~.ListProcessesRequest], + Awaitable[~.ListProcessesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processes' not in self._stubs: + self._stubs['list_processes'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/ListProcesses', + request_serializer=lva_service.ListProcessesRequest.serialize, + response_deserializer=lva_service.ListProcessesResponse.deserialize, + ) + return self._stubs['list_processes'] + + @property + def get_process(self) -> Callable[ + [lva_service.GetProcessRequest], + Awaitable[lva_resources.Process]]: + r"""Return a callable for the get process method over gRPC. + + Gets details of a single Process. + + Returns: + Callable[[~.GetProcessRequest], + Awaitable[~.Process]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_process' not in self._stubs: + self._stubs['get_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/GetProcess', + request_serializer=lva_service.GetProcessRequest.serialize, + response_deserializer=lva_resources.Process.deserialize, + ) + return self._stubs['get_process'] + + @property + def create_process(self) -> Callable[ + [lva_service.CreateProcessRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create process method over gRPC. + + Creates a new Process in a given project and + location. + + Returns: + Callable[[~.CreateProcessRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_process' not in self._stubs: + self._stubs['create_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/CreateProcess', + request_serializer=lva_service.CreateProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_process'] + + @property + def update_process(self) -> Callable[ + [lva_service.UpdateProcessRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update process method over gRPC. + + Updates the parameters of a single Process. + + Returns: + Callable[[~.UpdateProcessRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_process' not in self._stubs: + self._stubs['update_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/UpdateProcess', + request_serializer=lva_service.UpdateProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_process'] + + @property + def delete_process(self) -> Callable[ + [lva_service.DeleteProcessRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete process method over gRPC. + + Deletes a single Process. + + Returns: + Callable[[~.DeleteProcessRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_process' not in self._stubs: + self._stubs['delete_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/DeleteProcess', + request_serializer=lva_service.DeleteProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_process'] + + @property + def batch_run_process(self) -> Callable[ + [lva_service.BatchRunProcessRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch run process method over gRPC. + + Run all of the processes to "completion". Max time + for each process is the LRO time limit. + + Returns: + Callable[[~.BatchRunProcessRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_process' not in self._stubs: + self._stubs['batch_run_process'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.LiveVideoAnalytics/BatchRunProcess', + request_serializer=lva_service.BatchRunProcessRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_process'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_public_operators: gapic_v1.method_async.wrap_method( + self.list_public_operators, + default_timeout=None, + client_info=client_info, + ), + self.resolve_operator_info: gapic_v1.method_async.wrap_method( + self.resolve_operator_info, + default_timeout=None, + client_info=client_info, + ), + self.list_operators: gapic_v1.method_async.wrap_method( + self.list_operators, + default_timeout=60.0, + client_info=client_info, + ), + self.get_operator: gapic_v1.method_async.wrap_method( + self.get_operator, + default_timeout=60.0, + client_info=client_info, + ), + self.create_operator: gapic_v1.method_async.wrap_method( + self.create_operator, + default_timeout=300.0, + client_info=client_info, + ), + self.update_operator: gapic_v1.method_async.wrap_method( + self.update_operator, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_operator: gapic_v1.method_async.wrap_method( + self.delete_operator, + default_timeout=60.0, + client_info=client_info, + ), + self.list_analyses: gapic_v1.method_async.wrap_method( + self.list_analyses, + default_timeout=60.0, + client_info=client_info, + ), + self.get_analysis: gapic_v1.method_async.wrap_method( + self.get_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.create_analysis: gapic_v1.method_async.wrap_method( + self.create_analysis, + default_timeout=300.0, + client_info=client_info, + ), + self.update_analysis: gapic_v1.method_async.wrap_method( + self.update_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_analysis: gapic_v1.method_async.wrap_method( + self.delete_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.list_processes: gapic_v1.method_async.wrap_method( + self.list_processes, + default_timeout=None, + client_info=client_info, + ), + self.get_process: gapic_v1.method_async.wrap_method( + self.get_process, + default_timeout=None, + client_info=client_info, + ), + self.create_process: gapic_v1.method_async.wrap_method( + self.create_process, + default_timeout=None, + client_info=client_info, + ), + self.update_process: gapic_v1.method_async.wrap_method( + self.update_process, + default_timeout=None, + client_info=client_info, + ), + self.delete_process: gapic_v1.method_async.wrap_method( + self.delete_process, + default_timeout=None, + client_info=client_info, + ), + self.batch_run_process: gapic_v1.method_async.wrap_method( + self.batch_run_process, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'LiveVideoAnalyticsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/rest.py new file mode 100644 index 000000000000..b99394685272 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/live_video_analytics/transports/rest.py @@ -0,0 +1,2683 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class LiveVideoAnalyticsRestInterceptor: + """Interceptor for LiveVideoAnalytics. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the LiveVideoAnalyticsRestTransport. + + .. code-block:: python + class MyCustomLiveVideoAnalyticsInterceptor(LiveVideoAnalyticsRestInterceptor): + def pre_batch_run_process(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_run_process(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_operator(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_operator(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_process(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_process(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_operator(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_operator(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_process(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_process(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_operator(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_operator(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_process(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_process(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_analyses(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_analyses(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_operators(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_operators(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_public_operators(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_public_operators(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_resolve_operator_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_resolve_operator_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_operator(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_operator(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_process(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_process(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LiveVideoAnalyticsRestTransport(interceptor=MyCustomLiveVideoAnalyticsInterceptor()) + client = LiveVideoAnalyticsClient(transport=transport) + + + """ + def pre_batch_run_process(self, request: lva_service.BatchRunProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.BatchRunProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_run_process + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_batch_run_process(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_run_process + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_create_analysis(self, request: lva_service.CreateAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.CreateAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_create_analysis(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_create_operator(self, request: lva_service.CreateOperatorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.CreateOperatorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_operator + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_create_operator(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_operator + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_create_process(self, request: lva_service.CreateProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.CreateProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_process + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_create_process(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_process + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_delete_analysis(self, request: lva_service.DeleteAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.DeleteAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_delete_analysis(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_delete_operator(self, request: lva_service.DeleteOperatorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.DeleteOperatorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operator + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_delete_operator(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_operator + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_delete_process(self, request: lva_service.DeleteProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.DeleteProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_process + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_delete_process(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_process + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_get_analysis(self, request: lva_service.GetAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.GetAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_analysis(self, response: lva_resources.Analysis) -> lva_resources.Analysis: + """Post-rpc interceptor for get_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_get_operator(self, request: lva_service.GetOperatorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.GetOperatorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operator + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_operator(self, response: lva_resources.Operator) -> lva_resources.Operator: + """Post-rpc interceptor for get_operator + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_get_process(self, request: lva_service.GetProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.GetProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_process + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_process(self, response: lva_resources.Process) -> lva_resources.Process: + """Post-rpc interceptor for get_process + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_analyses(self, request: lva_service.ListAnalysesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.ListAnalysesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_analyses + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_analyses(self, response: lva_service.ListAnalysesResponse) -> lva_service.ListAnalysesResponse: + """Post-rpc interceptor for list_analyses + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_operators(self, request: lva_service.ListOperatorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.ListOperatorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operators + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_operators(self, response: lva_service.ListOperatorsResponse) -> lva_service.ListOperatorsResponse: + """Post-rpc interceptor for list_operators + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_processes(self, request: lva_service.ListProcessesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.ListProcessesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processes + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_processes(self, response: lva_service.ListProcessesResponse) -> lva_service.ListProcessesResponse: + """Post-rpc interceptor for list_processes + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_public_operators(self, request: lva_service.ListPublicOperatorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.ListPublicOperatorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_public_operators + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_public_operators(self, response: lva_service.ListPublicOperatorsResponse) -> lva_service.ListPublicOperatorsResponse: + """Post-rpc interceptor for list_public_operators + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_resolve_operator_info(self, request: lva_service.ResolveOperatorInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.ResolveOperatorInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for resolve_operator_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_resolve_operator_info(self, response: lva_service.ResolveOperatorInfoResponse) -> lva_service.ResolveOperatorInfoResponse: + """Post-rpc interceptor for resolve_operator_info + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_update_analysis(self, request: lva_service.UpdateAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.UpdateAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_update_analysis(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_update_operator(self, request: lva_service.UpdateOperatorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.UpdateOperatorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_operator + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_update_operator(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_operator + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_update_process(self, request: lva_service.UpdateProcessRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.UpdateProcessRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_process + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_update_process(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_process + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LiveVideoAnalyticsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LiveVideoAnalyticsRestInterceptor + + +class LiveVideoAnalyticsRestTransport(LiveVideoAnalyticsTransport): + """REST backend transport for LiveVideoAnalytics. + + Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[LiveVideoAnalyticsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or LiveVideoAnalyticsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _BatchRunProcess(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("BatchRunProcess") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.BatchRunProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch run process method over HTTP. + + Args: + request (~.lva_service.BatchRunProcessRequest): + The request object. Request message for running the + processes in a batch. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/processes:batchRun', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_run_process(request, metadata) + pb_request = lva_service.BatchRunProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_run_process(resp) + return resp + + class _CreateAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("CreateAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "analysisId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.CreateAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create analysis method over HTTP. + + Args: + request (~.lva_service.CreateAnalysisRequest): + The request object. Message for creating an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/analyses', + 'body': 'analysis', + }, + ] + request, metadata = self._interceptor.pre_create_analysis(request, metadata) + pb_request = lva_service.CreateAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_analysis(resp) + return resp + + class _CreateOperator(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("CreateOperator") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "operatorId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.CreateOperatorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create operator method over HTTP. + + Args: + request (~.lva_service.CreateOperatorRequest): + The request object. Message for creating a Operator. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/operators', + 'body': 'operator', + }, + ] + request, metadata = self._interceptor.pre_create_operator(request, metadata) + pb_request = lva_service.CreateOperatorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_operator(resp) + return resp + + class _CreateProcess(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("CreateProcess") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "processId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.CreateProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create process method over HTTP. + + Args: + request (~.lva_service.CreateProcessRequest): + The request object. Message for creating a Process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/processes', + 'body': 'process', + }, + ] + request, metadata = self._interceptor.pre_create_process(request, metadata) + pb_request = lva_service.CreateProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_process(resp) + return resp + + class _DeleteAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("DeleteAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.DeleteAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete analysis method over HTTP. + + Args: + request (~.lva_service.DeleteAnalysisRequest): + The request object. Message for deleting an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/analyses/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_analysis(request, metadata) + pb_request = lva_service.DeleteAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_analysis(resp) + return resp + + class _DeleteOperator(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("DeleteOperator") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.DeleteOperatorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete operator method over HTTP. + + Args: + request (~.lva_service.DeleteOperatorRequest): + The request object. Message for deleting a Operator + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operators/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_operator(request, metadata) + pb_request = lva_service.DeleteOperatorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_operator(resp) + return resp + + class _DeleteProcess(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("DeleteProcess") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.DeleteProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete process method over HTTP. + + Args: + request (~.lva_service.DeleteProcessRequest): + The request object. Message for deleting a Process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/processes/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_process(request, metadata) + pb_request = lva_service.DeleteProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_process(resp) + return resp + + class _GetAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("GetAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.GetAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_resources.Analysis: + r"""Call the get analysis method over HTTP. + + Args: + request (~.lva_service.GetAnalysisRequest): + The request object. Message for getting an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_resources.Analysis: + Message describing the Analysis + object. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/analyses/*}', + }, + ] + request, metadata = self._interceptor.pre_get_analysis(request, metadata) + pb_request = lva_service.GetAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_resources.Analysis() + pb_resp = lva_resources.Analysis.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_analysis(resp) + return resp + + class _GetOperator(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("GetOperator") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.GetOperatorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_resources.Operator: + r"""Call the get operator method over HTTP. + + Args: + request (~.lva_service.GetOperatorRequest): + The request object. Message for getting a Operator. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_resources.Operator: + Message describing the Operator + object. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operators/*}', + }, + ] + request, metadata = self._interceptor.pre_get_operator(request, metadata) + pb_request = lva_service.GetOperatorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_resources.Operator() + pb_resp = lva_resources.Operator.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_operator(resp) + return resp + + class _GetProcess(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("GetProcess") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.GetProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_resources.Process: + r"""Call the get process method over HTTP. + + Args: + request (~.lva_service.GetProcessRequest): + The request object. Message for getting a Process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_resources.Process: + Message describing the Process + object. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/processes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_process(request, metadata) + pb_request = lva_service.GetProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_resources.Process() + pb_resp = lva_resources.Process.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_process(resp) + return resp + + class _ListAnalyses(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("ListAnalyses") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.ListAnalysesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_service.ListAnalysesResponse: + r"""Call the list analyses method over HTTP. + + Args: + request (~.lva_service.ListAnalysesRequest): + The request object. Message for requesting list of + Analyses + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_service.ListAnalysesResponse: + Message for response to listing + Analyses + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/analyses', + }, + ] + request, metadata = self._interceptor.pre_list_analyses(request, metadata) + pb_request = lva_service.ListAnalysesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_service.ListAnalysesResponse() + pb_resp = lva_service.ListAnalysesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_analyses(resp) + return resp + + class _ListOperators(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("ListOperators") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.ListOperatorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_service.ListOperatorsResponse: + r"""Call the list operators method over HTTP. + + Args: + request (~.lva_service.ListOperatorsRequest): + The request object. Message for requesting list of + Operators. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_service.ListOperatorsResponse: + Message for response to listing + Operators. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/operators', + }, + ] + request, metadata = self._interceptor.pre_list_operators(request, metadata) + pb_request = lva_service.ListOperatorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_service.ListOperatorsResponse() + pb_resp = lva_service.ListOperatorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_operators(resp) + return resp + + class _ListProcesses(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("ListProcesses") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.ListProcessesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_service.ListProcessesResponse: + r"""Call the list processes method over HTTP. + + Args: + request (~.lva_service.ListProcessesRequest): + The request object. Message for requesting list of + Processes. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_service.ListProcessesResponse: + Message for response to listing + Processes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/processes', + }, + ] + request, metadata = self._interceptor.pre_list_processes(request, metadata) + pb_request = lva_service.ListProcessesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_service.ListProcessesResponse() + pb_resp = lva_service.ListProcessesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processes(resp) + return resp + + class _ListPublicOperators(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("ListPublicOperators") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.ListPublicOperatorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_service.ListPublicOperatorsResponse: + r"""Call the list public operators method over HTTP. + + Args: + request (~.lva_service.ListPublicOperatorsRequest): + The request object. Request message of + ListPublicOperatorsRequest API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_service.ListPublicOperatorsResponse: + Response message of + ListPublicOperators API. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}:listPublicOperators', + }, + ] + request, metadata = self._interceptor.pre_list_public_operators(request, metadata) + pb_request = lva_service.ListPublicOperatorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_service.ListPublicOperatorsResponse() + pb_resp = lva_service.ListPublicOperatorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_public_operators(resp) + return resp + + class _ResolveOperatorInfo(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("ResolveOperatorInfo") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.ResolveOperatorInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_service.ResolveOperatorInfoResponse: + r"""Call the resolve operator info method over HTTP. + + Args: + request (~.lva_service.ResolveOperatorInfoRequest): + The request object. Request message for querying operator + info. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_service.ResolveOperatorInfoResponse: + Response message of + ResolveOperatorInfo API. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}:resolveOperatorInfo', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_resolve_operator_info(request, metadata) + pb_request = lva_service.ResolveOperatorInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_service.ResolveOperatorInfoResponse() + pb_resp = lva_service.ResolveOperatorInfoResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_resolve_operator_info(resp) + return resp + + class _UpdateAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("UpdateAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.UpdateAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update analysis method over HTTP. + + Args: + request (~.lva_service.UpdateAnalysisRequest): + The request object. Message for updating an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{analysis.name=projects/*/locations/*/clusters/*/analyses/*}', + 'body': 'analysis', + }, + ] + request, metadata = self._interceptor.pre_update_analysis(request, metadata) + pb_request = lva_service.UpdateAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_analysis(resp) + return resp + + class _UpdateOperator(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("UpdateOperator") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.UpdateOperatorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update operator method over HTTP. + + Args: + request (~.lva_service.UpdateOperatorRequest): + The request object. Message for updating a Operator. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{operator.name=projects/*/locations/*/operators/*}', + 'body': 'operator', + }, + ] + request, metadata = self._interceptor.pre_update_operator(request, metadata) + pb_request = lva_service.UpdateOperatorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_operator(resp) + return resp + + class _UpdateProcess(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("UpdateProcess") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.UpdateProcessRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update process method over HTTP. + + Args: + request (~.lva_service.UpdateProcessRequest): + The request object. Message for updating a Process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{process.name=projects/*/locations/*/clusters/*/processes/*}', + 'body': 'process', + }, + ] + request, metadata = self._interceptor.pre_update_process(request, metadata) + pb_request = lva_service.UpdateProcessRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_process(resp) + return resp + + @property + def batch_run_process(self) -> Callable[ + [lva_service.BatchRunProcessRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchRunProcess(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_operator(self) -> Callable[ + [lva_service.CreateOperatorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateOperator(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_process(self) -> Callable[ + [lva_service.CreateProcessRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateProcess(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_operator(self) -> Callable[ + [lva_service.DeleteOperatorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteOperator(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_process(self) -> Callable[ + [lva_service.DeleteProcessRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteProcess(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + lva_resources.Analysis]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operator(self) -> Callable[ + [lva_service.GetOperatorRequest], + lva_resources.Operator]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOperator(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_process(self) -> Callable[ + [lva_service.GetProcessRequest], + lva_resources.Process]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcess(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + lva_service.ListAnalysesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAnalyses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_operators(self) -> Callable[ + [lva_service.ListOperatorsRequest], + lva_service.ListOperatorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListOperators(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processes(self) -> Callable[ + [lva_service.ListProcessesRequest], + lva_service.ListProcessesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcesses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_public_operators(self) -> Callable[ + [lva_service.ListPublicOperatorsRequest], + lva_service.ListPublicOperatorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPublicOperators(self._session, self._host, self._interceptor) # type: ignore + + @property + def resolve_operator_info(self) -> Callable[ + [lva_service.ResolveOperatorInfoRequest], + lva_service.ResolveOperatorInfoResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ResolveOperatorInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_operator(self) -> Callable[ + [lva_service.UpdateOperatorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOperator(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_process(self) -> Callable[ + [lva_service.UpdateProcessRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateProcess(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LiveVideoAnalyticsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/__init__.py new file mode 100644 index 000000000000..f39d9fd3b046 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamingServiceClient +from .async_client import StreamingServiceAsyncClient + +__all__ = ( + 'StreamingServiceClient', + 'StreamingServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/async_client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/async_client.py new file mode 100644 index 000000000000..2a578d568945 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/async_client.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import streaming_resources +from google.cloud.visionai_v1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import StreamingServiceGrpcAsyncIOTransport +from .client import StreamingServiceClient + + +class StreamingServiceAsyncClient: + """Streaming service for receiving and sending packets.""" + + _client: StreamingServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = StreamingServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = StreamingServiceClient._DEFAULT_UNIVERSE + + series_path = staticmethod(StreamingServiceClient.series_path) + parse_series_path = staticmethod(StreamingServiceClient.parse_series_path) + common_billing_account_path = staticmethod(StreamingServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(StreamingServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(StreamingServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(StreamingServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(StreamingServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(StreamingServiceClient.parse_common_organization_path) + common_project_path = staticmethod(StreamingServiceClient.common_project_path) + parse_common_project_path = staticmethod(StreamingServiceClient.parse_common_project_path) + common_location_path = staticmethod(StreamingServiceClient.common_location_path) + parse_common_location_path = staticmethod(StreamingServiceClient.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: + StreamingServiceAsyncClient: The constructed client. + """ + return StreamingServiceClient.from_service_account_info.__func__(StreamingServiceAsyncClient, 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: + StreamingServiceAsyncClient: The constructed client. + """ + return StreamingServiceClient.from_service_account_file.__func__(StreamingServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return StreamingServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> StreamingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamingServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(StreamingServiceClient).get_transport_class, type(StreamingServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamingServiceTransport, Callable[..., StreamingServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streaming service async 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 (Optional[Union[str,StreamingServiceTransport,Callable[..., StreamingServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamingServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = StreamingServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + def send_packets(self, + requests: Optional[AsyncIterator[streaming_service.SendPacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[streaming_service.SendPacketsResponse]]: + r"""Send packets to the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_send_packets(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.send_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1.types.SendPacketsRequest`]): + The request object AsyncIterator. Request message for sending packets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1.types.SendPacketsResponse]: + Response message for sending packets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.send_packets] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_packets(self, + requests: Optional[AsyncIterator[streaming_service.ReceivePacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[streaming_service.ReceivePacketsResponse]]: + r"""Receive packets from the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_receive_packets(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1.types.ReceivePacketsRequest`]): + The request object AsyncIterator. Request message for receiving + packets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1.types.ReceivePacketsResponse]: + Response message from ReceivePackets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.receive_packets] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_events(self, + requests: Optional[AsyncIterator[streaming_service.ReceiveEventsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[streaming_service.ReceiveEventsResponse]]: + r"""Receive events given the stream name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_receive_events(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_events(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1.types.ReceiveEventsRequest`]): + The request object AsyncIterator. Request message for ReceiveEvents. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1.types.ReceiveEventsResponse]: + Response message for the + ReceiveEvents. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.receive_events] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def acquire_lease(self, + request: Optional[Union[streaming_service.AcquireLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""AcquireLease acquires a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_acquire_lease(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AcquireLeaseRequest( + ) + + # Make the request + response = await client.acquire_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.AcquireLeaseRequest, dict]]): + The request object. Request message for acquiring a + lease. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.AcquireLeaseRequest): + request = streaming_service.AcquireLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.acquire_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def renew_lease(self, + request: Optional[Union[streaming_service.RenewLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""RenewLease renews a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_renew_lease(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.RenewLeaseRequest( + ) + + # Make the request + response = await client.renew_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.RenewLeaseRequest, dict]]): + The request object. Request message for renewing a lease. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.RenewLeaseRequest): + request = streaming_service.RenewLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.renew_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def release_lease(self, + request: Optional[Union[streaming_service.ReleaseLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.ReleaseLeaseResponse: + r"""RleaseLease releases a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_release_lease(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ReleaseLeaseRequest( + ) + + # Make the request + response = await client.release_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ReleaseLeaseRequest, dict]]): + The request object. Request message for releasing lease. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ReleaseLeaseResponse: + Response message for release lease. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.ReleaseLeaseRequest): + request = streaming_service.ReleaseLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.release_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "StreamingServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamingServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/client.py new file mode 100644 index 000000000000..5a1fb115c0c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/client.py @@ -0,0 +1,1290 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import streaming_resources +from google.cloud.visionai_v1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import StreamingServiceGrpcTransport +from .transports.grpc_asyncio import StreamingServiceGrpcAsyncIOTransport +from .transports.rest import StreamingServiceRestTransport + + +class StreamingServiceClientMeta(type): + """Metaclass for the StreamingService 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[StreamingServiceTransport]] + _transport_registry["grpc"] = StreamingServiceGrpcTransport + _transport_registry["grpc_asyncio"] = StreamingServiceGrpcAsyncIOTransport + _transport_registry["rest"] = StreamingServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[StreamingServiceTransport]: + """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 StreamingServiceClient(metaclass=StreamingServiceClientMeta): + """Streaming service for receiving and sending packets.""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + StreamingServiceClient: 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: + StreamingServiceClient: 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) -> StreamingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamingServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def series_path(project: str,location: str,cluster: str,series: str,) -> str: + """Returns a fully-qualified series string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + + @staticmethod + def parse_series_path(path: str) -> Dict[str,str]: + """Parses a series path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/series/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = StreamingServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + StreamingServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamingServiceTransport, Callable[..., StreamingServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streaming service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,StreamingServiceTransport,Callable[..., StreamingServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamingServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StreamingServiceClient._read_environment_variables() + self._client_cert_source = StreamingServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = StreamingServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, StreamingServiceTransport) + if transport_provided: + # transport is a StreamingServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(StreamingServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + StreamingServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[StreamingServiceTransport], Callable[..., StreamingServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., StreamingServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def send_packets(self, + requests: Optional[Iterator[streaming_service.SendPacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[streaming_service.SendPacketsResponse]: + r"""Send packets to the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_send_packets(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.send_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1.types.SendPacketsRequest]): + The request object iterator. Request message for sending packets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1.types.SendPacketsResponse]: + Response message for sending packets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_packets] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_packets(self, + requests: Optional[Iterator[streaming_service.ReceivePacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[streaming_service.ReceivePacketsResponse]: + r"""Receive packets from the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_receive_packets(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1.types.ReceivePacketsRequest]): + The request object iterator. Request message for receiving + packets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1.types.ReceivePacketsResponse]: + Response message from ReceivePackets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.receive_packets] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_events(self, + requests: Optional[Iterator[streaming_service.ReceiveEventsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[streaming_service.ReceiveEventsResponse]: + r"""Receive events given the stream name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_receive_events(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_events(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1.types.ReceiveEventsRequest]): + The request object iterator. Request message for ReceiveEvents. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1.types.ReceiveEventsResponse]: + Response message for the + ReceiveEvents. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.receive_events] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def acquire_lease(self, + request: Optional[Union[streaming_service.AcquireLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""AcquireLease acquires a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_acquire_lease(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.AcquireLeaseRequest( + ) + + # Make the request + response = client.acquire_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.AcquireLeaseRequest, dict]): + The request object. Request message for acquiring a + lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.AcquireLeaseRequest): + request = streaming_service.AcquireLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.acquire_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def renew_lease(self, + request: Optional[Union[streaming_service.RenewLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""RenewLease renews a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_renew_lease(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.RenewLeaseRequest( + ) + + # Make the request + response = client.renew_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.RenewLeaseRequest, dict]): + The request object. Request message for renewing a lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.RenewLeaseRequest): + request = streaming_service.RenewLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.renew_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def release_lease(self, + request: Optional[Union[streaming_service.ReleaseLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.ReleaseLeaseResponse: + r"""RleaseLease releases a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_release_lease(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ReleaseLeaseRequest( + ) + + # Make the request + response = client.release_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ReleaseLeaseRequest, dict]): + The request object. Request message for releasing lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ReleaseLeaseResponse: + Response message for release lease. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.ReleaseLeaseRequest): + request = streaming_service.ReleaseLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.release_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "StreamingServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamingServiceClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/__init__.py new file mode 100644 index 000000000000..6136e80c250d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamingServiceTransport +from .grpc import StreamingServiceGrpcTransport +from .grpc_asyncio import StreamingServiceGrpcAsyncIOTransport +from .rest import StreamingServiceRestTransport +from .rest import StreamingServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StreamingServiceTransport]] +_transport_registry['grpc'] = StreamingServiceGrpcTransport +_transport_registry['grpc_asyncio'] = StreamingServiceGrpcAsyncIOTransport +_transport_registry['rest'] = StreamingServiceRestTransport + +__all__ = ( + 'StreamingServiceTransport', + 'StreamingServiceGrpcTransport', + 'StreamingServiceGrpcAsyncIOTransport', + 'StreamingServiceRestTransport', + 'StreamingServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/base.py new file mode 100644 index 000000000000..661f52c5ec62 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/base.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class StreamingServiceTransport(abc.ABC): + """Abstract transport class for StreamingService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.send_packets: gapic_v1.method.wrap_method( + self.send_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_packets: gapic_v1.method.wrap_method( + self.receive_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_events: gapic_v1.method.wrap_method( + self.receive_events, + default_timeout=None, + client_info=client_info, + ), + self.acquire_lease: gapic_v1.method.wrap_method( + self.acquire_lease, + default_timeout=None, + client_info=client_info, + ), + self.renew_lease: gapic_v1.method.wrap_method( + self.renew_lease, + default_timeout=None, + client_info=client_info, + ), + self.release_lease: gapic_v1.method.wrap_method( + self.release_lease, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + Union[ + streaming_service.SendPacketsResponse, + Awaitable[streaming_service.SendPacketsResponse] + ]]: + raise NotImplementedError() + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + Union[ + streaming_service.ReceivePacketsResponse, + Awaitable[streaming_service.ReceivePacketsResponse] + ]]: + raise NotImplementedError() + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + Union[ + streaming_service.ReceiveEventsResponse, + Awaitable[streaming_service.ReceiveEventsResponse] + ]]: + raise NotImplementedError() + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + Union[ + streaming_service.Lease, + Awaitable[streaming_service.Lease] + ]]: + raise NotImplementedError() + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + Union[ + streaming_service.Lease, + Awaitable[streaming_service.Lease] + ]]: + raise NotImplementedError() + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + Union[ + streaming_service.ReleaseLeaseResponse, + Awaitable[streaming_service.ReleaseLeaseResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'StreamingServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/grpc.py new file mode 100644 index 000000000000..f7d4696f99cb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/grpc.py @@ -0,0 +1,475 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamingServiceTransport, DEFAULT_CLIENT_INFO + + +class StreamingServiceGrpcTransport(StreamingServiceTransport): + """gRPC backend transport for StreamingService. + + Streaming service for receiving and sending packets. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance 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 isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[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 send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + streaming_service.SendPacketsResponse]: + r"""Return a callable for the send packets method over gRPC. + + Send packets to the series. + + Returns: + Callable[[~.SendPacketsRequest], + ~.SendPacketsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'send_packets' not in self._stubs: + self._stubs['send_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.StreamingService/SendPackets', + request_serializer=streaming_service.SendPacketsRequest.serialize, + response_deserializer=streaming_service.SendPacketsResponse.deserialize, + ) + return self._stubs['send_packets'] + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + streaming_service.ReceivePacketsResponse]: + r"""Return a callable for the receive packets method over gRPC. + + Receive packets from the series. + + Returns: + Callable[[~.ReceivePacketsRequest], + ~.ReceivePacketsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_packets' not in self._stubs: + self._stubs['receive_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.StreamingService/ReceivePackets', + request_serializer=streaming_service.ReceivePacketsRequest.serialize, + response_deserializer=streaming_service.ReceivePacketsResponse.deserialize, + ) + return self._stubs['receive_packets'] + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + streaming_service.ReceiveEventsResponse]: + r"""Return a callable for the receive events method over gRPC. + + Receive events given the stream name. + + Returns: + Callable[[~.ReceiveEventsRequest], + ~.ReceiveEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_events' not in self._stubs: + self._stubs['receive_events'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.StreamingService/ReceiveEvents', + request_serializer=streaming_service.ReceiveEventsRequest.serialize, + response_deserializer=streaming_service.ReceiveEventsResponse.deserialize, + ) + return self._stubs['receive_events'] + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + streaming_service.Lease]: + r"""Return a callable for the acquire lease method over gRPC. + + AcquireLease acquires a lease. + + Returns: + Callable[[~.AcquireLeaseRequest], + ~.Lease]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acquire_lease' not in self._stubs: + self._stubs['acquire_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamingService/AcquireLease', + request_serializer=streaming_service.AcquireLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['acquire_lease'] + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + streaming_service.Lease]: + r"""Return a callable for the renew lease method over gRPC. + + RenewLease renews a lease. + + Returns: + Callable[[~.RenewLeaseRequest], + ~.Lease]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'renew_lease' not in self._stubs: + self._stubs['renew_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamingService/RenewLease', + request_serializer=streaming_service.RenewLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['renew_lease'] + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + streaming_service.ReleaseLeaseResponse]: + r"""Return a callable for the release lease method over gRPC. + + RleaseLease releases a lease. + + Returns: + Callable[[~.ReleaseLeaseRequest], + ~.ReleaseLeaseResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'release_lease' not in self._stubs: + self._stubs['release_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamingService/ReleaseLease', + request_serializer=streaming_service.ReleaseLeaseRequest.serialize, + response_deserializer=streaming_service.ReleaseLeaseResponse.deserialize, + ) + return self._stubs['release_lease'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'StreamingServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..9c69b5716953 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/grpc_asyncio.py @@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamingServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import StreamingServiceGrpcTransport + + +class StreamingServiceGrpcAsyncIOTransport(StreamingServiceTransport): + """gRPC AsyncIO backend transport for StreamingService. + + Streaming service for receiving and sending packets. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance 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 isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + Awaitable[streaming_service.SendPacketsResponse]]: + r"""Return a callable for the send packets method over gRPC. + + Send packets to the series. + + Returns: + Callable[[~.SendPacketsRequest], + Awaitable[~.SendPacketsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'send_packets' not in self._stubs: + self._stubs['send_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.StreamingService/SendPackets', + request_serializer=streaming_service.SendPacketsRequest.serialize, + response_deserializer=streaming_service.SendPacketsResponse.deserialize, + ) + return self._stubs['send_packets'] + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + Awaitable[streaming_service.ReceivePacketsResponse]]: + r"""Return a callable for the receive packets method over gRPC. + + Receive packets from the series. + + Returns: + Callable[[~.ReceivePacketsRequest], + Awaitable[~.ReceivePacketsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_packets' not in self._stubs: + self._stubs['receive_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.StreamingService/ReceivePackets', + request_serializer=streaming_service.ReceivePacketsRequest.serialize, + response_deserializer=streaming_service.ReceivePacketsResponse.deserialize, + ) + return self._stubs['receive_packets'] + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + Awaitable[streaming_service.ReceiveEventsResponse]]: + r"""Return a callable for the receive events method over gRPC. + + Receive events given the stream name. + + Returns: + Callable[[~.ReceiveEventsRequest], + Awaitable[~.ReceiveEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_events' not in self._stubs: + self._stubs['receive_events'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.StreamingService/ReceiveEvents', + request_serializer=streaming_service.ReceiveEventsRequest.serialize, + response_deserializer=streaming_service.ReceiveEventsResponse.deserialize, + ) + return self._stubs['receive_events'] + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + Awaitable[streaming_service.Lease]]: + r"""Return a callable for the acquire lease method over gRPC. + + AcquireLease acquires a lease. + + Returns: + Callable[[~.AcquireLeaseRequest], + Awaitable[~.Lease]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acquire_lease' not in self._stubs: + self._stubs['acquire_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamingService/AcquireLease', + request_serializer=streaming_service.AcquireLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['acquire_lease'] + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + Awaitable[streaming_service.Lease]]: + r"""Return a callable for the renew lease method over gRPC. + + RenewLease renews a lease. + + Returns: + Callable[[~.RenewLeaseRequest], + Awaitable[~.Lease]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'renew_lease' not in self._stubs: + self._stubs['renew_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamingService/RenewLease', + request_serializer=streaming_service.RenewLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['renew_lease'] + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + Awaitable[streaming_service.ReleaseLeaseResponse]]: + r"""Return a callable for the release lease method over gRPC. + + RleaseLease releases a lease. + + Returns: + Callable[[~.ReleaseLeaseRequest], + Awaitable[~.ReleaseLeaseResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'release_lease' not in self._stubs: + self._stubs['release_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamingService/ReleaseLease', + request_serializer=streaming_service.ReleaseLeaseRequest.serialize, + response_deserializer=streaming_service.ReleaseLeaseResponse.deserialize, + ) + return self._stubs['release_lease'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.send_packets: gapic_v1.method_async.wrap_method( + self.send_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_packets: gapic_v1.method_async.wrap_method( + self.receive_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_events: gapic_v1.method_async.wrap_method( + self.receive_events, + default_timeout=None, + client_info=client_info, + ), + self.acquire_lease: gapic_v1.method_async.wrap_method( + self.acquire_lease, + default_timeout=None, + client_info=client_info, + ), + self.renew_lease: gapic_v1.method_async.wrap_method( + self.renew_lease, + default_timeout=None, + client_info=client_info, + ), + self.release_lease: gapic_v1.method_async.wrap_method( + self.release_lease, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'StreamingServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/rest.py new file mode 100644 index 000000000000..6ebb9468cb04 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streaming_service/transports/rest.py @@ -0,0 +1,934 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1.types import streaming_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import StreamingServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class StreamingServiceRestInterceptor: + """Interceptor for StreamingService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the StreamingServiceRestTransport. + + .. code-block:: python + class MyCustomStreamingServiceInterceptor(StreamingServiceRestInterceptor): + def pre_acquire_lease(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_acquire_lease(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_release_lease(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_release_lease(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_renew_lease(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_renew_lease(self, response): + logging.log(f"Received response: {response}") + return response + + transport = StreamingServiceRestTransport(interceptor=MyCustomStreamingServiceInterceptor()) + client = StreamingServiceClient(transport=transport) + + + """ + def pre_acquire_lease(self, request: streaming_service.AcquireLeaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streaming_service.AcquireLeaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for acquire_lease + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_acquire_lease(self, response: streaming_service.Lease) -> streaming_service.Lease: + """Post-rpc interceptor for acquire_lease + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_release_lease(self, request: streaming_service.ReleaseLeaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streaming_service.ReleaseLeaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for release_lease + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_release_lease(self, response: streaming_service.ReleaseLeaseResponse) -> streaming_service.ReleaseLeaseResponse: + """Post-rpc interceptor for release_lease + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_renew_lease(self, request: streaming_service.RenewLeaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streaming_service.RenewLeaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for renew_lease + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_renew_lease(self, response: streaming_service.Lease) -> streaming_service.Lease: + """Post-rpc interceptor for renew_lease + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class StreamingServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: StreamingServiceRestInterceptor + + +class StreamingServiceRestTransport(StreamingServiceTransport): + """REST backend transport for StreamingService. + + Streaming service for receiving and sending packets. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[StreamingServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or StreamingServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AcquireLease(StreamingServiceRestStub): + def __hash__(self): + return hash("AcquireLease") + + def __call__(self, + request: streaming_service.AcquireLeaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streaming_service.Lease: + r"""Call the acquire lease method over HTTP. + + Args: + request (~.streaming_service.AcquireLeaseRequest): + The request object. Request message for acquiring a + lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streaming_service.Lease: + The lease message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{series=projects/*/locations/*/clusters/*/series/*}:acquireLease', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_acquire_lease(request, metadata) + pb_request = streaming_service.AcquireLeaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streaming_service.Lease() + pb_resp = streaming_service.Lease.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_acquire_lease(resp) + return resp + + class _ReceiveEvents(StreamingServiceRestStub): + def __hash__(self): + return hash("ReceiveEvents") + + def __call__(self, + request: streaming_service.ReceiveEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method ReceiveEvents is not available over REST transport" + ) + class _ReceivePackets(StreamingServiceRestStub): + def __hash__(self): + return hash("ReceivePackets") + + def __call__(self, + request: streaming_service.ReceivePacketsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method ReceivePackets is not available over REST transport" + ) + class _ReleaseLease(StreamingServiceRestStub): + def __hash__(self): + return hash("ReleaseLease") + + def __call__(self, + request: streaming_service.ReleaseLeaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streaming_service.ReleaseLeaseResponse: + r"""Call the release lease method over HTTP. + + Args: + request (~.streaming_service.ReleaseLeaseRequest): + The request object. Request message for releasing lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streaming_service.ReleaseLeaseResponse: + Response message for release lease. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{series=projects/*/locations/*/clusters/*/series/*}:releaseLease', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_release_lease(request, metadata) + pb_request = streaming_service.ReleaseLeaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streaming_service.ReleaseLeaseResponse() + pb_resp = streaming_service.ReleaseLeaseResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_release_lease(resp) + return resp + + class _RenewLease(StreamingServiceRestStub): + def __hash__(self): + return hash("RenewLease") + + def __call__(self, + request: streaming_service.RenewLeaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streaming_service.Lease: + r"""Call the renew lease method over HTTP. + + Args: + request (~.streaming_service.RenewLeaseRequest): + The request object. Request message for renewing a lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streaming_service.Lease: + The lease message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{series=projects/*/locations/*/clusters/*/series/*}:renewLease', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_renew_lease(request, metadata) + pb_request = streaming_service.RenewLeaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streaming_service.Lease() + pb_resp = streaming_service.Lease.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_renew_lease(resp) + return resp + + class _SendPackets(StreamingServiceRestStub): + def __hash__(self): + return hash("SendPackets") + + def __call__(self, + request: streaming_service.SendPacketsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method SendPackets is not available over REST transport" + ) + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + streaming_service.Lease]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AcquireLease(self._session, self._host, self._interceptor) # type: ignore + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + streaming_service.ReceiveEventsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReceiveEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + streaming_service.ReceivePacketsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReceivePackets(self._session, self._host, self._interceptor) # type: ignore + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + streaming_service.ReleaseLeaseResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReleaseLease(self._session, self._host, self._interceptor) # type: ignore + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + streaming_service.Lease]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RenewLease(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + streaming_service.SendPacketsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SendPackets(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'StreamingServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/__init__.py new file mode 100644 index 000000000000..ee9eade81318 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamsServiceClient +from .async_client import StreamsServiceAsyncClient + +__all__ = ( + 'StreamsServiceClient', + 'StreamsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/async_client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/async_client.py new file mode 100644 index 000000000000..a0510641a29d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/async_client.py @@ -0,0 +1,3260 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.streams_service import pagers +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import StreamsServiceGrpcAsyncIOTransport +from .client import StreamsServiceClient + + +class StreamsServiceAsyncClient: + """Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + """ + + _client: StreamsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = StreamsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = StreamsServiceClient._DEFAULT_UNIVERSE + + channel_path = staticmethod(StreamsServiceClient.channel_path) + parse_channel_path = staticmethod(StreamsServiceClient.parse_channel_path) + cluster_path = staticmethod(StreamsServiceClient.cluster_path) + parse_cluster_path = staticmethod(StreamsServiceClient.parse_cluster_path) + event_path = staticmethod(StreamsServiceClient.event_path) + parse_event_path = staticmethod(StreamsServiceClient.parse_event_path) + series_path = staticmethod(StreamsServiceClient.series_path) + parse_series_path = staticmethod(StreamsServiceClient.parse_series_path) + stream_path = staticmethod(StreamsServiceClient.stream_path) + parse_stream_path = staticmethod(StreamsServiceClient.parse_stream_path) + common_billing_account_path = staticmethod(StreamsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(StreamsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(StreamsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(StreamsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(StreamsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(StreamsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(StreamsServiceClient.common_project_path) + parse_common_project_path = staticmethod(StreamsServiceClient.parse_common_project_path) + common_location_path = staticmethod(StreamsServiceClient.common_location_path) + parse_common_location_path = staticmethod(StreamsServiceClient.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: + StreamsServiceAsyncClient: The constructed client. + """ + return StreamsServiceClient.from_service_account_info.__func__(StreamsServiceAsyncClient, 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: + StreamsServiceAsyncClient: The constructed client. + """ + return StreamsServiceClient.from_service_account_file.__func__(StreamsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return StreamsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> StreamsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(StreamsServiceClient).get_transport_class, type(StreamsServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamsServiceTransport, Callable[..., StreamsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streams service async 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 (Optional[Union[str,StreamsServiceTransport,Callable[..., StreamsServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = StreamsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_clusters(self, + request: Optional[Union[streams_service.ListClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListClustersAsyncPager: + r"""Lists Clusters in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_clusters(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListClustersRequest, dict]]): + The request object. Message for requesting list of + Clusters. + parent (:class:`str`): + Required. Parent value for + ListClustersRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListClustersAsyncPager: + Message for response to listing + Clusters. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListClustersRequest): + request = streams_service.ListClustersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_clusters] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListClustersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_cluster(self, + request: Optional[Union[streams_service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetClusterRequest, dict]]): + The request object. Message for getting a Cluster. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Cluster: + Message describing the Cluster + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetClusterRequest): + request = streams_service.GetClusterRequest(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._client._transport._wrapped_methods[self._client._transport.get_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_cluster(self, + request: Optional[Union[streams_service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[common.Cluster] = None, + cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Cluster in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateClusterRequest, dict]]): + The request object. Message for creating a Cluster. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.visionai_v1.types.Cluster`): + Required. The resource being created. + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Cluster` Message + describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, cluster, cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateClusterRequest): + request = streams_service.CreateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_cluster(self, + request: Optional[Union[streams_service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[common.Cluster] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateClusterRequest, dict]]): + The request object. Message for updating a Cluster. + cluster (:class:`google.cloud.visionai_v1.types.Cluster`): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Cluster` Message + describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateClusterRequest): + request = streams_service.UpdateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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._client._transport._wrapped_methods[self._client._transport.update_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster.name", request.cluster.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_cluster(self, + request: Optional[Union[streams_service.DeleteClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteClusterRequest, dict]]): + The request object. Message for deleting a Cluster. + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteClusterRequest): + request = streams_service.DeleteClusterRequest(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._client._transport._wrapped_methods[self._client._transport.delete_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_streams(self, + request: Optional[Union[streams_service.ListStreamsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListStreamsAsyncPager: + r"""Lists Streams in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_streams(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListStreamsRequest, dict]]): + The request object. Message for requesting list of + Streams. + parent (:class:`str`): + Required. Parent value for + ListStreamsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListStreamsAsyncPager: + Message for response to listing + Streams. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListStreamsRequest): + request = streams_service.ListStreamsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_streams] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListStreamsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_stream(self, + request: Optional[Union[streams_service.GetStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Stream: + r"""Gets details of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = await client.get_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetStreamRequest, dict]]): + The request object. Message for getting a Stream. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Stream: + Message describing the Stream object. + The Stream and the Event resources are + many to many; i.e., each Stream resource + can associate to many Event resources + and each Event resource can associate to + many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetStreamRequest): + request = streams_service.GetStreamRequest(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._client._transport._wrapped_methods[self._client._transport.get_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_stream(self, + request: Optional[Union[streams_service.CreateStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + stream: Optional[streams_resources.Stream] = None, + stream_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Stream in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateStreamRequest, dict]]): + The request object. Message for creating a Stream. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream (:class:`google.cloud.visionai_v1.types.Stream`): + Required. The resource being created. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``stream_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, stream, stream_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateStreamRequest): + request = streams_service.CreateStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if stream is not None: + request.stream = stream + if stream_id is not None: + request.stream_id = stream_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_stream(self, + request: Optional[Union[streams_service.UpdateStreamRequest, dict]] = None, + *, + stream: Optional[streams_resources.Stream] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateStreamRequest, dict]]): + The request object. Message for updating a Stream. + stream (:class:`google.cloud.visionai_v1.types.Stream`): + Required. The resource being updated. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Stream resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateStreamRequest): + request = streams_service.UpdateStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + 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._client._transport._wrapped_methods[self._client._transport.update_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream.name", request.stream.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_stream(self, + request: Optional[Union[streams_service.DeleteStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteStreamRequest, dict]]): + The request object. Message for deleting a Stream. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteStreamRequest): + request = streams_service.DeleteStreamRequest(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._client._transport._wrapped_methods[self._client._transport.delete_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_stream_thumbnail(self, + request: Optional[Union[streams_service.GetStreamThumbnailRequest, dict]] = None, + *, + stream: Optional[str] = None, + gcs_object_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Gets the thumbnail (image snapshot) of a single + Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_stream_thumbnail(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamThumbnailRequest( + stream="stream_value", + gcs_object_name="gcs_object_name_value", + ) + + # Make the request + operation = client.get_stream_thumbnail(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetStreamThumbnailRequest, dict]]): + The request object. Message for getting the thumbnail of + a Stream. + stream (:class:`str`): + Required. The name of the stream for + to get the thumbnail from. + + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gcs_object_name (:class:`str`): + Required. The name of the GCS object + to store the thumbnail image. + + This corresponds to the ``gcs_object_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.GetStreamThumbnailResponse` Message for the response of GetStreamThumbnail. The empty response message + indicates the thumbnail image has been uploaded to + GCS successfully. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream, gcs_object_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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetStreamThumbnailRequest): + request = streams_service.GetStreamThumbnailRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + if gcs_object_name is not None: + request.gcs_object_name = gcs_object_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_stream_thumbnail] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream", request.stream), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_service.GetStreamThumbnailResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_stream_hls_token(self, + request: Optional[Union[streams_service.GenerateStreamHlsTokenRequest, dict]] = None, + *, + stream: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_service.GenerateStreamHlsTokenResponse: + r"""Generate the JWT auth token required to get the + stream HLS contents. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = await client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GenerateStreamHlsTokenRequest, dict]]): + The request object. Request message for getting the auth + token to access the stream HLS contents. + stream (:class:`str`): + Required. The name of the stream. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.GenerateStreamHlsTokenResponse: + Response message for + GenerateStreamHlsToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GenerateStreamHlsTokenRequest): + request = streams_service.GenerateStreamHlsTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_stream_hls_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream", request.stream), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_events(self, + request: Optional[Union[streams_service.ListEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEventsAsyncPager: + r"""Lists Events in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_events(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListEventsRequest, dict]]): + The request object. Message for requesting list of + Events. + parent (:class:`str`): + Required. Parent value for + ListEventsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListEventsAsyncPager: + Message for response to listing + Events. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListEventsRequest): + request = streams_service.ListEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_events] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListEventsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_event(self, + request: Optional[Union[streams_service.GetEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Event: + r"""Gets details of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetEventRequest, dict]]): + The request object. Message for getting a Event. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Event: + Message describing the Event object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetEventRequest): + request = streams_service.GetEventRequest(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._client._transport._wrapped_methods[self._client._transport.get_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_event(self, + request: Optional[Union[streams_service.CreateEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + event: Optional[streams_resources.Event] = None, + event_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Event in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateEventRequest, dict]]): + The request object. Message for creating a Event. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event (:class:`google.cloud.visionai_v1.types.Event`): + Required. The resource being created. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``event_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Event` Message + describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event, event_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateEventRequest): + request = streams_service.CreateEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event is not None: + request.event = event + if event_id is not None: + request.event_id = event_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_event(self, + request: Optional[Union[streams_service.UpdateEventRequest, dict]] = None, + *, + event: Optional[streams_resources.Event] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateEventRequest, dict]]): + The request object. Message for updating a Event. + event (:class:`google.cloud.visionai_v1.types.Event`): + Required. The resource being updated. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Event resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Event` Message + describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateEventRequest): + request = streams_service.UpdateEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event is not None: + request.event = event + 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._client._transport._wrapped_methods[self._client._transport.update_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event.name", request.event.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_event(self, + request: Optional[Union[streams_service.DeleteEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteEventRequest, dict]]): + The request object. Message for deleting a Event. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteEventRequest): + request = streams_service.DeleteEventRequest(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._client._transport._wrapped_methods[self._client._transport.delete_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_series(self, + request: Optional[Union[streams_service.ListSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSeriesAsyncPager: + r"""Lists Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListSeriesRequest, dict]]): + The request object. Message for requesting list of + Series. + parent (:class:`str`): + Required. Parent value for + ListSeriesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListSeriesAsyncPager: + Message for response to listing + Series. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListSeriesRequest): + request = streams_service.ListSeriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListSeriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_series(self, + request: Optional[Union[streams_service.GetSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Series: + r"""Gets details of a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_series(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetSeriesRequest, dict]]): + The request object. Message for getting a Series. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Series: + Message describing the Series object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetSeriesRequest): + request = streams_service.GetSeriesRequest(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._client._transport._wrapped_methods[self._client._transport.get_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_series(self, + request: Optional[Union[streams_service.CreateSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + series: Optional[streams_resources.Series] = None, + series_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateSeriesRequest, dict]]): + The request object. Message for creating a Series. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series (:class:`google.cloud.visionai_v1.types.Series`): + Required. The resource being created. + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``series_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Series` Message + describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, series, series_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateSeriesRequest): + request = streams_service.CreateSeriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if series is not None: + request.series = series + if series_id is not None: + request.series_id = series_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_series(self, + request: Optional[Union[streams_service.UpdateSeriesRequest, dict]] = None, + *, + series: Optional[streams_resources.Series] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateSeriesRequest, dict]]): + The request object. Message for updating a Series. + series (:class:`google.cloud.visionai_v1.types.Series`): + Required. The resource being updated + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Series resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Series` Message + describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([series, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateSeriesRequest): + request = streams_service.UpdateSeriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if series is not None: + request.series = series + 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._client._transport._wrapped_methods[self._client._transport.update_series] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series.name", request.series.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_series(self, + request: Optional[Union[streams_service.DeleteSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteSeriesRequest, dict]]): + The request object. Message for deleting a Series. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteSeriesRequest): + request = streams_service.DeleteSeriesRequest(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._client._transport._wrapped_methods[self._client._transport.delete_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def materialize_channel(self, + request: Optional[Union[streams_service.MaterializeChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[streams_resources.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Materialize a channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_materialize_channel(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + channel = visionai_v1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.MaterializeChannelRequest, dict]]): + The request object. Message for materializing a channel. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel (:class:`google.cloud.visionai_v1.types.Channel`): + Required. The resource being created. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_id (:class:`str`): + Required. Id of the channel. + This corresponds to the ``channel_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Channel` Message + describing the Channel object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel, channel_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.MaterializeChannelRequest): + request = streams_service.MaterializeChannelRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel is not None: + request.channel = channel + if channel_id is not None: + request.channel_id = channel_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.materialize_channel] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Channel, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "StreamsServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/client.py new file mode 100644 index 000000000000..0b442d1385c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/client.py @@ -0,0 +1,3633 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.streams_service import pagers +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import StreamsServiceGrpcTransport +from .transports.grpc_asyncio import StreamsServiceGrpcAsyncIOTransport +from .transports.rest import StreamsServiceRestTransport + + +class StreamsServiceClientMeta(type): + """Metaclass for the StreamsService 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[StreamsServiceTransport]] + _transport_registry["grpc"] = StreamsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = StreamsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = StreamsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[StreamsServiceTransport]: + """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 StreamsServiceClient(metaclass=StreamsServiceClientMeta): + """Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + StreamsServiceClient: 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: + StreamsServiceClient: 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) -> StreamsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def channel_path(project: str,location: str,cluster: str,channel: str,) -> str: + """Returns a fully-qualified channel string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/channels/{channel}".format(project=project, location=location, cluster=cluster, channel=channel, ) + + @staticmethod + def parse_channel_path(path: str) -> Dict[str,str]: + """Parses a channel path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/channels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def event_path(project: str,location: str,cluster: str,event: str,) -> str: + """Returns a fully-qualified event string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/events/{event}".format(project=project, location=location, cluster=cluster, event=event, ) + + @staticmethod + def parse_event_path(path: str) -> Dict[str,str]: + """Parses a event path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/events/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def series_path(project: str,location: str,cluster: str,series: str,) -> str: + """Returns a fully-qualified series string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + + @staticmethod + def parse_series_path(path: str) -> Dict[str,str]: + """Parses a series path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/series/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def stream_path(project: str,location: str,cluster: str,stream: str,) -> str: + """Returns a fully-qualified stream string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + + @staticmethod + def parse_stream_path(path: str) -> Dict[str,str]: + """Parses a stream path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/streams/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = StreamsServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + StreamsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamsServiceTransport, Callable[..., StreamsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streams service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,StreamsServiceTransport,Callable[..., StreamsServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StreamsServiceClient._read_environment_variables() + self._client_cert_source = StreamsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = StreamsServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, StreamsServiceTransport) + if transport_provided: + # transport is a StreamsServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(StreamsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + StreamsServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[StreamsServiceTransport], Callable[..., StreamsServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., StreamsServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_clusters(self, + request: Optional[Union[streams_service.ListClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListClustersPager: + r"""Lists Clusters in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_clusters(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListClustersRequest, dict]): + The request object. Message for requesting list of + Clusters. + parent (str): + Required. Parent value for + ListClustersRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListClustersPager: + Message for response to listing + Clusters. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListClustersRequest): + request = streams_service.ListClustersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_clusters] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListClustersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_cluster(self, + request: Optional[Union[streams_service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetClusterRequest, dict]): + The request object. Message for getting a Cluster. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Cluster: + Message describing the Cluster + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetClusterRequest): + request = streams_service.GetClusterRequest(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_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_cluster(self, + request: Optional[Union[streams_service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[common.Cluster] = None, + cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Cluster in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateClusterRequest, dict]): + The request object. Message for creating a Cluster. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.visionai_v1.types.Cluster): + Required. The resource being created. + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Cluster` Message + describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, cluster, cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateClusterRequest): + request = streams_service.CreateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_cluster(self, + request: Optional[Union[streams_service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[common.Cluster] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateClusterRequest, dict]): + The request object. Message for updating a Cluster. + cluster (google.cloud.visionai_v1.types.Cluster): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Cluster` Message + describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateClusterRequest): + request = streams_service.UpdateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster.name", request.cluster.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_cluster(self, + request: Optional[Union[streams_service.DeleteClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteClusterRequest, dict]): + The request object. Message for deleting a Cluster. + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteClusterRequest): + request = streams_service.DeleteClusterRequest(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_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_streams(self, + request: Optional[Union[streams_service.ListStreamsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListStreamsPager: + r"""Lists Streams in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_streams(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListStreamsRequest, dict]): + The request object. Message for requesting list of + Streams. + parent (str): + Required. Parent value for + ListStreamsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListStreamsPager: + Message for response to listing + Streams. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListStreamsRequest): + request = streams_service.ListStreamsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_streams] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListStreamsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_stream(self, + request: Optional[Union[streams_service.GetStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Stream: + r"""Gets details of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = client.get_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetStreamRequest, dict]): + The request object. Message for getting a Stream. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Stream: + Message describing the Stream object. + The Stream and the Event resources are + many to many; i.e., each Stream resource + can associate to many Event resources + and each Event resource can associate to + many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetStreamRequest): + request = streams_service.GetStreamRequest(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_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_stream(self, + request: Optional[Union[streams_service.CreateStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + stream: Optional[streams_resources.Stream] = None, + stream_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Stream in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateStreamRequest, dict]): + The request object. Message for creating a Stream. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream (google.cloud.visionai_v1.types.Stream): + Required. The resource being created. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``stream_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, stream, stream_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateStreamRequest): + request = streams_service.CreateStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if stream is not None: + request.stream = stream + if stream_id is not None: + request.stream_id = stream_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_stream(self, + request: Optional[Union[streams_service.UpdateStreamRequest, dict]] = None, + *, + stream: Optional[streams_resources.Stream] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateStreamRequest, dict]): + The request object. Message for updating a Stream. + stream (google.cloud.visionai_v1.types.Stream): + Required. The resource being updated. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Stream resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateStreamRequest): + request = streams_service.UpdateStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + 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_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream.name", request.stream.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_stream(self, + request: Optional[Union[streams_service.DeleteStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteStreamRequest, dict]): + The request object. Message for deleting a Stream. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteStreamRequest): + request = streams_service.DeleteStreamRequest(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_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_stream_thumbnail(self, + request: Optional[Union[streams_service.GetStreamThumbnailRequest, dict]] = None, + *, + stream: Optional[str] = None, + gcs_object_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Gets the thumbnail (image snapshot) of a single + Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_stream_thumbnail(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamThumbnailRequest( + stream="stream_value", + gcs_object_name="gcs_object_name_value", + ) + + # Make the request + operation = client.get_stream_thumbnail(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetStreamThumbnailRequest, dict]): + The request object. Message for getting the thumbnail of + a Stream. + stream (str): + Required. The name of the stream for + to get the thumbnail from. + + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gcs_object_name (str): + Required. The name of the GCS object + to store the thumbnail image. + + This corresponds to the ``gcs_object_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.GetStreamThumbnailResponse` Message for the response of GetStreamThumbnail. The empty response message + indicates the thumbnail image has been uploaded to + GCS successfully. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream, gcs_object_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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetStreamThumbnailRequest): + request = streams_service.GetStreamThumbnailRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + if gcs_object_name is not None: + request.gcs_object_name = gcs_object_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_stream_thumbnail] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream", request.stream), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_service.GetStreamThumbnailResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_stream_hls_token(self, + request: Optional[Union[streams_service.GenerateStreamHlsTokenRequest, dict]] = None, + *, + stream: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_service.GenerateStreamHlsTokenResponse: + r"""Generate the JWT auth token required to get the + stream HLS contents. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GenerateStreamHlsTokenRequest, dict]): + The request object. Request message for getting the auth + token to access the stream HLS contents. + stream (str): + Required. The name of the stream. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.GenerateStreamHlsTokenResponse: + Response message for + GenerateStreamHlsToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GenerateStreamHlsTokenRequest): + request = streams_service.GenerateStreamHlsTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_stream_hls_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream", request.stream), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_events(self, + request: Optional[Union[streams_service.ListEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEventsPager: + r"""Lists Events in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_events(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListEventsRequest, dict]): + The request object. Message for requesting list of + Events. + parent (str): + Required. Parent value for + ListEventsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListEventsPager: + Message for response to listing + Events. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListEventsRequest): + request = streams_service.ListEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_events] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListEventsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_event(self, + request: Optional[Union[streams_service.GetEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Event: + r"""Gets details of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetEventRequest, dict]): + The request object. Message for getting a Event. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Event: + Message describing the Event object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetEventRequest): + request = streams_service.GetEventRequest(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_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_event(self, + request: Optional[Union[streams_service.CreateEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + event: Optional[streams_resources.Event] = None, + event_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Event in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateEventRequest, dict]): + The request object. Message for creating a Event. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event (google.cloud.visionai_v1.types.Event): + Required. The resource being created. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``event_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Event` Message + describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event, event_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateEventRequest): + request = streams_service.CreateEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event is not None: + request.event = event + if event_id is not None: + request.event_id = event_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_event(self, + request: Optional[Union[streams_service.UpdateEventRequest, dict]] = None, + *, + event: Optional[streams_resources.Event] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateEventRequest, dict]): + The request object. Message for updating a Event. + event (google.cloud.visionai_v1.types.Event): + Required. The resource being updated. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Event resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Event` Message + describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateEventRequest): + request = streams_service.UpdateEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event is not None: + request.event = event + 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_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event.name", request.event.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_event(self, + request: Optional[Union[streams_service.DeleteEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteEventRequest, dict]): + The request object. Message for deleting a Event. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteEventRequest): + request = streams_service.DeleteEventRequest(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_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_series(self, + request: Optional[Union[streams_service.ListSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSeriesPager: + r"""Lists Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListSeriesRequest, dict]): + The request object. Message for requesting list of + Series. + parent (str): + Required. Parent value for + ListSeriesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.streams_service.pagers.ListSeriesPager: + Message for response to listing + Series. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListSeriesRequest): + request = streams_service.ListSeriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListSeriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_series(self, + request: Optional[Union[streams_service.GetSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Series: + r"""Gets details of a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = client.get_series(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetSeriesRequest, dict]): + The request object. Message for getting a Series. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Series: + Message describing the Series object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetSeriesRequest): + request = streams_service.GetSeriesRequest(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_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_series(self, + request: Optional[Union[streams_service.CreateSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + series: Optional[streams_resources.Series] = None, + series_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateSeriesRequest, dict]): + The request object. Message for creating a Series. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series (google.cloud.visionai_v1.types.Series): + Required. The resource being created. + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``series_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Series` Message + describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, series, series_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateSeriesRequest): + request = streams_service.CreateSeriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if series is not None: + request.series = series + if series_id is not None: + request.series_id = series_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_series(self, + request: Optional[Union[streams_service.UpdateSeriesRequest, dict]] = None, + *, + series: Optional[streams_resources.Series] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateSeriesRequest, dict]): + The request object. Message for updating a Series. + series (google.cloud.visionai_v1.types.Series): + Required. The resource being updated + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Series resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Series` Message + describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([series, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateSeriesRequest): + request = streams_service.UpdateSeriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if series is not None: + request.series = series + 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_series] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series.name", request.series.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_series(self, + request: Optional[Union[streams_service.DeleteSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteSeriesRequest, dict]): + The request object. Message for deleting a Series. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteSeriesRequest): + request = streams_service.DeleteSeriesRequest(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_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def materialize_channel(self, + request: Optional[Union[streams_service.MaterializeChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[streams_resources.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Materialize a channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_materialize_channel(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + channel = visionai_v1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.MaterializeChannelRequest, dict]): + The request object. Message for materializing a channel. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel (google.cloud.visionai_v1.types.Channel): + Required. The resource being created. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_id (str): + Required. Id of the channel. + This corresponds to the ``channel_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.Channel` Message + describing the Channel object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel, channel_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.MaterializeChannelRequest): + request = streams_service.MaterializeChannelRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel is not None: + request.channel = channel + if channel_id is not None: + request.channel_id = channel_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.materialize_channel] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Channel, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "StreamsServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamsServiceClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/pagers.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/pagers.py new file mode 100644 index 000000000000..712328609123 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/pagers.py @@ -0,0 +1,504 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service + + +class ListClustersPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListClustersResponse` + 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[..., streams_service.ListClustersResponse], + request: streams_service.ListClustersRequest, + response: streams_service.ListClustersResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListClustersRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListClustersResponse): + 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 = streams_service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[common.Cluster]: + for page in self.pages: + yield from page.clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClustersAsyncPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListClustersResponse` + 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[streams_service.ListClustersResponse]], + request: streams_service.ListClustersRequest, + response: streams_service.ListClustersResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListClustersRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListClustersResponse): + 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 = streams_service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[common.Cluster]: + async def async_generator(): + async for page in self.pages: + for response in page.clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListStreamsPager: + """A pager for iterating through ``list_streams`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListStreamsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``streams`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListStreams`` requests and continue to iterate + through the ``streams`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListStreamsResponse` + 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[..., streams_service.ListStreamsResponse], + request: streams_service.ListStreamsRequest, + response: streams_service.ListStreamsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListStreamsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListStreamsResponse): + 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 = streams_service.ListStreamsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListStreamsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[streams_resources.Stream]: + for page in self.pages: + yield from page.streams + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListStreamsAsyncPager: + """A pager for iterating through ``list_streams`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListStreamsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``streams`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListStreams`` requests and continue to iterate + through the ``streams`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListStreamsResponse` + 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[streams_service.ListStreamsResponse]], + request: streams_service.ListStreamsRequest, + response: streams_service.ListStreamsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListStreamsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListStreamsResponse): + 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 = streams_service.ListStreamsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListStreamsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[streams_resources.Stream]: + async def async_generator(): + async for page in self.pages: + for response in page.streams: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventsPager: + """A pager for iterating through ``list_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvents`` requests and continue to iterate + through the ``events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListEventsResponse` + 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[..., streams_service.ListEventsResponse], + request: streams_service.ListEventsRequest, + response: streams_service.ListEventsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListEventsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListEventsResponse): + 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 = streams_service.ListEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[streams_resources.Event]: + for page in self.pages: + yield from page.events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventsAsyncPager: + """A pager for iterating through ``list_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvents`` requests and continue to iterate + through the ``events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListEventsResponse` + 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[streams_service.ListEventsResponse]], + request: streams_service.ListEventsRequest, + response: streams_service.ListEventsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListEventsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListEventsResponse): + 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 = streams_service.ListEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[streams_resources.Event]: + async def async_generator(): + async for page in self.pages: + for response in page.events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSeriesPager: + """A pager for iterating through ``list_series`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListSeriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``series`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSeries`` requests and continue to iterate + through the ``series`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListSeriesResponse` + 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[..., streams_service.ListSeriesResponse], + request: streams_service.ListSeriesRequest, + response: streams_service.ListSeriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListSeriesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListSeriesResponse): + 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 = streams_service.ListSeriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListSeriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[streams_resources.Series]: + for page in self.pages: + yield from page.series + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSeriesAsyncPager: + """A pager for iterating through ``list_series`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListSeriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``series`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSeries`` requests and continue to iterate + through the ``series`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListSeriesResponse` + 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[streams_service.ListSeriesResponse]], + request: streams_service.ListSeriesRequest, + response: streams_service.ListSeriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListSeriesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListSeriesResponse): + 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 = streams_service.ListSeriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListSeriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[streams_resources.Series]: + async def async_generator(): + async for page in self.pages: + for response in page.series: + 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/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/__init__.py new file mode 100644 index 000000000000..6fec714da909 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamsServiceTransport +from .grpc import StreamsServiceGrpcTransport +from .grpc_asyncio import StreamsServiceGrpcAsyncIOTransport +from .rest import StreamsServiceRestTransport +from .rest import StreamsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StreamsServiceTransport]] +_transport_registry['grpc'] = StreamsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = StreamsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = StreamsServiceRestTransport + +__all__ = ( + 'StreamsServiceTransport', + 'StreamsServiceGrpcTransport', + 'StreamsServiceGrpcAsyncIOTransport', + 'StreamsServiceRestTransport', + 'StreamsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/base.py new file mode 100644 index 000000000000..82824f9f5ee1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/base.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class StreamsServiceTransport(abc.ABC): + """Abstract transport class for StreamsService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_clusters: gapic_v1.method.wrap_method( + self.list_clusters, + default_timeout=None, + client_info=client_info, + ), + self.get_cluster: gapic_v1.method.wrap_method( + self.get_cluster, + default_timeout=None, + client_info=client_info, + ), + self.create_cluster: gapic_v1.method.wrap_method( + self.create_cluster, + default_timeout=None, + client_info=client_info, + ), + self.update_cluster: gapic_v1.method.wrap_method( + self.update_cluster, + default_timeout=None, + client_info=client_info, + ), + self.delete_cluster: gapic_v1.method.wrap_method( + self.delete_cluster, + default_timeout=None, + client_info=client_info, + ), + self.list_streams: gapic_v1.method.wrap_method( + self.list_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_stream: gapic_v1.method.wrap_method( + self.get_stream, + default_timeout=None, + client_info=client_info, + ), + self.create_stream: gapic_v1.method.wrap_method( + self.create_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_stream: gapic_v1.method.wrap_method( + self.update_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_stream: gapic_v1.method.wrap_method( + self.delete_stream, + default_timeout=None, + client_info=client_info, + ), + self.get_stream_thumbnail: gapic_v1.method.wrap_method( + self.get_stream_thumbnail, + default_timeout=None, + client_info=client_info, + ), + self.generate_stream_hls_token: gapic_v1.method.wrap_method( + self.generate_stream_hls_token, + default_timeout=None, + client_info=client_info, + ), + self.list_events: gapic_v1.method.wrap_method( + self.list_events, + default_timeout=None, + client_info=client_info, + ), + self.get_event: gapic_v1.method.wrap_method( + self.get_event, + default_timeout=None, + client_info=client_info, + ), + self.create_event: gapic_v1.method.wrap_method( + self.create_event, + default_timeout=None, + client_info=client_info, + ), + self.update_event: gapic_v1.method.wrap_method( + self.update_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_event: gapic_v1.method.wrap_method( + self.delete_event, + default_timeout=None, + client_info=client_info, + ), + self.list_series: gapic_v1.method.wrap_method( + self.list_series, + default_timeout=None, + client_info=client_info, + ), + self.get_series: gapic_v1.method.wrap_method( + self.get_series, + default_timeout=None, + client_info=client_info, + ), + self.create_series: gapic_v1.method.wrap_method( + self.create_series, + default_timeout=None, + client_info=client_info, + ), + self.update_series: gapic_v1.method.wrap_method( + self.update_series, + default_timeout=None, + client_info=client_info, + ), + self.delete_series: gapic_v1.method.wrap_method( + self.delete_series, + default_timeout=None, + client_info=client_info, + ), + self.materialize_channel: gapic_v1.method.wrap_method( + self.materialize_channel, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + Union[ + streams_service.ListClustersResponse, + Awaitable[streams_service.ListClustersResponse] + ]]: + raise NotImplementedError() + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + Union[ + common.Cluster, + Awaitable[common.Cluster] + ]]: + raise NotImplementedError() + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + Union[ + streams_service.ListStreamsResponse, + Awaitable[streams_service.ListStreamsResponse] + ]]: + raise NotImplementedError() + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + Union[ + streams_resources.Stream, + Awaitable[streams_resources.Stream] + ]]: + raise NotImplementedError() + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_stream_thumbnail(self) -> Callable[ + [streams_service.GetStreamThumbnailRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + Union[ + streams_service.GenerateStreamHlsTokenResponse, + Awaitable[streams_service.GenerateStreamHlsTokenResponse] + ]]: + raise NotImplementedError() + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + Union[ + streams_service.ListEventsResponse, + Awaitable[streams_service.ListEventsResponse] + ]]: + raise NotImplementedError() + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + Union[ + streams_resources.Event, + Awaitable[streams_resources.Event] + ]]: + raise NotImplementedError() + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + Union[ + streams_service.ListSeriesResponse, + Awaitable[streams_service.ListSeriesResponse] + ]]: + raise NotImplementedError() + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + Union[ + streams_resources.Series, + Awaitable[streams_resources.Series] + ]]: + raise NotImplementedError() + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'StreamsServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/grpc.py new file mode 100644 index 000000000000..45696db240ef --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/grpc.py @@ -0,0 +1,944 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamsServiceTransport, DEFAULT_CLIENT_INFO + + +class StreamsServiceGrpcTransport(StreamsServiceTransport): + """gRPC backend transport for StreamsService. + + Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + streams_service.ListClustersResponse]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + ~.ListClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListClusters', + request_serializer=streams_service.ListClustersRequest.serialize, + response_deserializer=streams_service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + common.Cluster]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + ~.Cluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetCluster', + request_serializer=streams_service.GetClusterRequest.serialize, + response_deserializer=common.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateCluster', + request_serializer=streams_service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateCluster', + request_serializer=streams_service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteCluster', + request_serializer=streams_service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + streams_service.ListStreamsResponse]: + r"""Return a callable for the list streams method over gRPC. + + Lists Streams in a given project and location. + + Returns: + Callable[[~.ListStreamsRequest], + ~.ListStreamsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_streams' not in self._stubs: + self._stubs['list_streams'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListStreams', + request_serializer=streams_service.ListStreamsRequest.serialize, + response_deserializer=streams_service.ListStreamsResponse.deserialize, + ) + return self._stubs['list_streams'] + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + streams_resources.Stream]: + r"""Return a callable for the get stream method over gRPC. + + Gets details of a single Stream. + + Returns: + Callable[[~.GetStreamRequest], + ~.Stream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_stream' not in self._stubs: + self._stubs['get_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetStream', + request_serializer=streams_service.GetStreamRequest.serialize, + response_deserializer=streams_resources.Stream.deserialize, + ) + return self._stubs['get_stream'] + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + operations_pb2.Operation]: + r"""Return a callable for the create stream method over gRPC. + + Creates a new Stream in a given project and location. + + Returns: + Callable[[~.CreateStreamRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_stream' not in self._stubs: + self._stubs['create_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateStream', + request_serializer=streams_service.CreateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_stream'] + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + operations_pb2.Operation]: + r"""Return a callable for the update stream method over gRPC. + + Updates the parameters of a single Stream. + + Returns: + Callable[[~.UpdateStreamRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_stream' not in self._stubs: + self._stubs['update_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateStream', + request_serializer=streams_service.UpdateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_stream'] + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete stream method over gRPC. + + Deletes a single Stream. + + Returns: + Callable[[~.DeleteStreamRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_stream' not in self._stubs: + self._stubs['delete_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteStream', + request_serializer=streams_service.DeleteStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_stream'] + + @property + def get_stream_thumbnail(self) -> Callable[ + [streams_service.GetStreamThumbnailRequest], + operations_pb2.Operation]: + r"""Return a callable for the get stream thumbnail method over gRPC. + + Gets the thumbnail (image snapshot) of a single + Stream. + + Returns: + Callable[[~.GetStreamThumbnailRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_stream_thumbnail' not in self._stubs: + self._stubs['get_stream_thumbnail'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetStreamThumbnail', + request_serializer=streams_service.GetStreamThumbnailRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['get_stream_thumbnail'] + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + streams_service.GenerateStreamHlsTokenResponse]: + r"""Return a callable for the generate stream hls token method over gRPC. + + Generate the JWT auth token required to get the + stream HLS contents. + + Returns: + Callable[[~.GenerateStreamHlsTokenRequest], + ~.GenerateStreamHlsTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_stream_hls_token' not in self._stubs: + self._stubs['generate_stream_hls_token'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GenerateStreamHlsToken', + request_serializer=streams_service.GenerateStreamHlsTokenRequest.serialize, + response_deserializer=streams_service.GenerateStreamHlsTokenResponse.deserialize, + ) + return self._stubs['generate_stream_hls_token'] + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + streams_service.ListEventsResponse]: + r"""Return a callable for the list events method over gRPC. + + Lists Events in a given project and location. + + Returns: + Callable[[~.ListEventsRequest], + ~.ListEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_events' not in self._stubs: + self._stubs['list_events'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListEvents', + request_serializer=streams_service.ListEventsRequest.serialize, + response_deserializer=streams_service.ListEventsResponse.deserialize, + ) + return self._stubs['list_events'] + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + streams_resources.Event]: + r"""Return a callable for the get event method over gRPC. + + Gets details of a single Event. + + Returns: + Callable[[~.GetEventRequest], + ~.Event]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event' not in self._stubs: + self._stubs['get_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetEvent', + request_serializer=streams_service.GetEventRequest.serialize, + response_deserializer=streams_resources.Event.deserialize, + ) + return self._stubs['get_event'] + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + operations_pb2.Operation]: + r"""Return a callable for the create event method over gRPC. + + Creates a new Event in a given project and location. + + Returns: + Callable[[~.CreateEventRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event' not in self._stubs: + self._stubs['create_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateEvent', + request_serializer=streams_service.CreateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_event'] + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + operations_pb2.Operation]: + r"""Return a callable for the update event method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateEventRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event' not in self._stubs: + self._stubs['update_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateEvent', + request_serializer=streams_service.UpdateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_event'] + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete event method over gRPC. + + Deletes a single Event. + + Returns: + Callable[[~.DeleteEventRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_event' not in self._stubs: + self._stubs['delete_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteEvent', + request_serializer=streams_service.DeleteEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_event'] + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + streams_service.ListSeriesResponse]: + r"""Return a callable for the list series method over gRPC. + + Lists Series in a given project and location. + + Returns: + Callable[[~.ListSeriesRequest], + ~.ListSeriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['list_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListSeries', + request_serializer=streams_service.ListSeriesRequest.serialize, + response_deserializer=streams_service.ListSeriesResponse.deserialize, + ) + return self._stubs['list_series'] + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + streams_resources.Series]: + r"""Return a callable for the get series method over gRPC. + + Gets details of a single Series. + + Returns: + Callable[[~.GetSeriesRequest], + ~.Series]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['get_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetSeries', + request_serializer=streams_service.GetSeriesRequest.serialize, + response_deserializer=streams_resources.Series.deserialize, + ) + return self._stubs['get_series'] + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the create series method over gRPC. + + Creates a new Series in a given project and location. + + Returns: + Callable[[~.CreateSeriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_series' not in self._stubs: + self._stubs['create_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateSeries', + request_serializer=streams_service.CreateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_series'] + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the update series method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateSeriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_series' not in self._stubs: + self._stubs['update_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateSeries', + request_serializer=streams_service.UpdateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_series'] + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete series method over gRPC. + + Deletes a single Series. + + Returns: + Callable[[~.DeleteSeriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_series' not in self._stubs: + self._stubs['delete_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteSeries', + request_serializer=streams_service.DeleteSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_series'] + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + operations_pb2.Operation]: + r"""Return a callable for the materialize channel method over gRPC. + + Materialize a channel. + + Returns: + Callable[[~.MaterializeChannelRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'materialize_channel' not in self._stubs: + self._stubs['materialize_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/MaterializeChannel', + request_serializer=streams_service.MaterializeChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['materialize_channel'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'StreamsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..915c0d661623 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/grpc_asyncio.py @@ -0,0 +1,1064 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import StreamsServiceGrpcTransport + + +class StreamsServiceGrpcAsyncIOTransport(StreamsServiceTransport): + """gRPC AsyncIO backend transport for StreamsService. + + Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + Awaitable[streams_service.ListClustersResponse]]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + Awaitable[~.ListClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListClusters', + request_serializer=streams_service.ListClustersRequest.serialize, + response_deserializer=streams_service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + Awaitable[common.Cluster]]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + Awaitable[~.Cluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetCluster', + request_serializer=streams_service.GetClusterRequest.serialize, + response_deserializer=common.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateCluster', + request_serializer=streams_service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateCluster', + request_serializer=streams_service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteCluster', + request_serializer=streams_service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + Awaitable[streams_service.ListStreamsResponse]]: + r"""Return a callable for the list streams method over gRPC. + + Lists Streams in a given project and location. + + Returns: + Callable[[~.ListStreamsRequest], + Awaitable[~.ListStreamsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_streams' not in self._stubs: + self._stubs['list_streams'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListStreams', + request_serializer=streams_service.ListStreamsRequest.serialize, + response_deserializer=streams_service.ListStreamsResponse.deserialize, + ) + return self._stubs['list_streams'] + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + Awaitable[streams_resources.Stream]]: + r"""Return a callable for the get stream method over gRPC. + + Gets details of a single Stream. + + Returns: + Callable[[~.GetStreamRequest], + Awaitable[~.Stream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_stream' not in self._stubs: + self._stubs['get_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetStream', + request_serializer=streams_service.GetStreamRequest.serialize, + response_deserializer=streams_resources.Stream.deserialize, + ) + return self._stubs['get_stream'] + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create stream method over gRPC. + + Creates a new Stream in a given project and location. + + Returns: + Callable[[~.CreateStreamRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_stream' not in self._stubs: + self._stubs['create_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateStream', + request_serializer=streams_service.CreateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_stream'] + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update stream method over gRPC. + + Updates the parameters of a single Stream. + + Returns: + Callable[[~.UpdateStreamRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_stream' not in self._stubs: + self._stubs['update_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateStream', + request_serializer=streams_service.UpdateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_stream'] + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete stream method over gRPC. + + Deletes a single Stream. + + Returns: + Callable[[~.DeleteStreamRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_stream' not in self._stubs: + self._stubs['delete_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteStream', + request_serializer=streams_service.DeleteStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_stream'] + + @property + def get_stream_thumbnail(self) -> Callable[ + [streams_service.GetStreamThumbnailRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the get stream thumbnail method over gRPC. + + Gets the thumbnail (image snapshot) of a single + Stream. + + Returns: + Callable[[~.GetStreamThumbnailRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_stream_thumbnail' not in self._stubs: + self._stubs['get_stream_thumbnail'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetStreamThumbnail', + request_serializer=streams_service.GetStreamThumbnailRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['get_stream_thumbnail'] + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + Awaitable[streams_service.GenerateStreamHlsTokenResponse]]: + r"""Return a callable for the generate stream hls token method over gRPC. + + Generate the JWT auth token required to get the + stream HLS contents. + + Returns: + Callable[[~.GenerateStreamHlsTokenRequest], + Awaitable[~.GenerateStreamHlsTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_stream_hls_token' not in self._stubs: + self._stubs['generate_stream_hls_token'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GenerateStreamHlsToken', + request_serializer=streams_service.GenerateStreamHlsTokenRequest.serialize, + response_deserializer=streams_service.GenerateStreamHlsTokenResponse.deserialize, + ) + return self._stubs['generate_stream_hls_token'] + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + Awaitable[streams_service.ListEventsResponse]]: + r"""Return a callable for the list events method over gRPC. + + Lists Events in a given project and location. + + Returns: + Callable[[~.ListEventsRequest], + Awaitable[~.ListEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_events' not in self._stubs: + self._stubs['list_events'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListEvents', + request_serializer=streams_service.ListEventsRequest.serialize, + response_deserializer=streams_service.ListEventsResponse.deserialize, + ) + return self._stubs['list_events'] + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + Awaitable[streams_resources.Event]]: + r"""Return a callable for the get event method over gRPC. + + Gets details of a single Event. + + Returns: + Callable[[~.GetEventRequest], + Awaitable[~.Event]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event' not in self._stubs: + self._stubs['get_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetEvent', + request_serializer=streams_service.GetEventRequest.serialize, + response_deserializer=streams_resources.Event.deserialize, + ) + return self._stubs['get_event'] + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create event method over gRPC. + + Creates a new Event in a given project and location. + + Returns: + Callable[[~.CreateEventRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event' not in self._stubs: + self._stubs['create_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateEvent', + request_serializer=streams_service.CreateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_event'] + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update event method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateEventRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event' not in self._stubs: + self._stubs['update_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateEvent', + request_serializer=streams_service.UpdateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_event'] + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete event method over gRPC. + + Deletes a single Event. + + Returns: + Callable[[~.DeleteEventRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_event' not in self._stubs: + self._stubs['delete_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteEvent', + request_serializer=streams_service.DeleteEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_event'] + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + Awaitable[streams_service.ListSeriesResponse]]: + r"""Return a callable for the list series method over gRPC. + + Lists Series in a given project and location. + + Returns: + Callable[[~.ListSeriesRequest], + Awaitable[~.ListSeriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['list_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/ListSeries', + request_serializer=streams_service.ListSeriesRequest.serialize, + response_deserializer=streams_service.ListSeriesResponse.deserialize, + ) + return self._stubs['list_series'] + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + Awaitable[streams_resources.Series]]: + r"""Return a callable for the get series method over gRPC. + + Gets details of a single Series. + + Returns: + Callable[[~.GetSeriesRequest], + Awaitable[~.Series]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['get_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/GetSeries', + request_serializer=streams_service.GetSeriesRequest.serialize, + response_deserializer=streams_resources.Series.deserialize, + ) + return self._stubs['get_series'] + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create series method over gRPC. + + Creates a new Series in a given project and location. + + Returns: + Callable[[~.CreateSeriesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_series' not in self._stubs: + self._stubs['create_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/CreateSeries', + request_serializer=streams_service.CreateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_series'] + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update series method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateSeriesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_series' not in self._stubs: + self._stubs['update_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/UpdateSeries', + request_serializer=streams_service.UpdateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_series'] + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete series method over gRPC. + + Deletes a single Series. + + Returns: + Callable[[~.DeleteSeriesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_series' not in self._stubs: + self._stubs['delete_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/DeleteSeries', + request_serializer=streams_service.DeleteSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_series'] + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the materialize channel method over gRPC. + + Materialize a channel. + + Returns: + Callable[[~.MaterializeChannelRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'materialize_channel' not in self._stubs: + self._stubs['materialize_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.StreamsService/MaterializeChannel', + request_serializer=streams_service.MaterializeChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['materialize_channel'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_clusters: gapic_v1.method_async.wrap_method( + self.list_clusters, + default_timeout=None, + client_info=client_info, + ), + self.get_cluster: gapic_v1.method_async.wrap_method( + self.get_cluster, + default_timeout=None, + client_info=client_info, + ), + self.create_cluster: gapic_v1.method_async.wrap_method( + self.create_cluster, + default_timeout=None, + client_info=client_info, + ), + self.update_cluster: gapic_v1.method_async.wrap_method( + self.update_cluster, + default_timeout=None, + client_info=client_info, + ), + self.delete_cluster: gapic_v1.method_async.wrap_method( + self.delete_cluster, + default_timeout=None, + client_info=client_info, + ), + self.list_streams: gapic_v1.method_async.wrap_method( + self.list_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_stream: gapic_v1.method_async.wrap_method( + self.get_stream, + default_timeout=None, + client_info=client_info, + ), + self.create_stream: gapic_v1.method_async.wrap_method( + self.create_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_stream: gapic_v1.method_async.wrap_method( + self.update_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_stream: gapic_v1.method_async.wrap_method( + self.delete_stream, + default_timeout=None, + client_info=client_info, + ), + self.get_stream_thumbnail: gapic_v1.method_async.wrap_method( + self.get_stream_thumbnail, + default_timeout=None, + client_info=client_info, + ), + self.generate_stream_hls_token: gapic_v1.method_async.wrap_method( + self.generate_stream_hls_token, + default_timeout=None, + client_info=client_info, + ), + self.list_events: gapic_v1.method_async.wrap_method( + self.list_events, + default_timeout=None, + client_info=client_info, + ), + self.get_event: gapic_v1.method_async.wrap_method( + self.get_event, + default_timeout=None, + client_info=client_info, + ), + self.create_event: gapic_v1.method_async.wrap_method( + self.create_event, + default_timeout=None, + client_info=client_info, + ), + self.update_event: gapic_v1.method_async.wrap_method( + self.update_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_event: gapic_v1.method_async.wrap_method( + self.delete_event, + default_timeout=None, + client_info=client_info, + ), + self.list_series: gapic_v1.method_async.wrap_method( + self.list_series, + default_timeout=None, + client_info=client_info, + ), + self.get_series: gapic_v1.method_async.wrap_method( + self.get_series, + default_timeout=None, + client_info=client_info, + ), + self.create_series: gapic_v1.method_async.wrap_method( + self.create_series, + default_timeout=None, + client_info=client_info, + ), + self.update_series: gapic_v1.method_async.wrap_method( + self.update_series, + default_timeout=None, + client_info=client_info, + ), + self.delete_series: gapic_v1.method_async.wrap_method( + self.delete_series, + default_timeout=None, + client_info=client_info, + ), + self.materialize_channel: gapic_v1.method_async.wrap_method( + self.materialize_channel, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'StreamsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/rest.py new file mode 100644 index 000000000000..52be9cd00f4e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/streams_service/transports/rest.py @@ -0,0 +1,3261 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import StreamsServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class StreamsServiceRestInterceptor: + """Interceptor for StreamsService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the StreamsServiceRestTransport. + + .. code-block:: python + class MyCustomStreamsServiceInterceptor(StreamsServiceRestInterceptor): + def pre_create_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_stream_hls_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_stream_hls_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_stream_thumbnail(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_stream_thumbnail(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_streams(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_streams(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_materialize_channel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_materialize_channel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_stream(self, response): + logging.log(f"Received response: {response}") + return response + + transport = StreamsServiceRestTransport(interceptor=MyCustomStreamsServiceInterceptor()) + client = StreamsServiceClient(transport=transport) + + + """ + def pre_create_cluster(self, request: streams_service.CreateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_create_event(self, request: streams_service.CreateEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_event(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_create_series(self, request: streams_service.CreateSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_series(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_create_stream(self, request: streams_service.CreateStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_stream(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_cluster(self, request: streams_service.DeleteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_event(self, request: streams_service.DeleteEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_event(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_series(self, request: streams_service.DeleteSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_series(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_stream(self, request: streams_service.DeleteStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_stream(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_generate_stream_hls_token(self, request: streams_service.GenerateStreamHlsTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GenerateStreamHlsTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_stream_hls_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_generate_stream_hls_token(self, response: streams_service.GenerateStreamHlsTokenResponse) -> streams_service.GenerateStreamHlsTokenResponse: + """Post-rpc interceptor for generate_stream_hls_token + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_cluster(self, request: streams_service.GetClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_cluster(self, response: common.Cluster) -> common.Cluster: + """Post-rpc interceptor for get_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_event(self, request: streams_service.GetEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_event(self, response: streams_resources.Event) -> streams_resources.Event: + """Post-rpc interceptor for get_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_series(self, request: streams_service.GetSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_series(self, response: streams_resources.Series) -> streams_resources.Series: + """Post-rpc interceptor for get_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_stream(self, request: streams_service.GetStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_stream(self, response: streams_resources.Stream) -> streams_resources.Stream: + """Post-rpc interceptor for get_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_stream_thumbnail(self, request: streams_service.GetStreamThumbnailRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetStreamThumbnailRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_stream_thumbnail + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_stream_thumbnail(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for get_stream_thumbnail + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_clusters(self, request: streams_service.ListClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_clusters(self, response: streams_service.ListClustersResponse) -> streams_service.ListClustersResponse: + """Post-rpc interceptor for list_clusters + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_events(self, request: streams_service.ListEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_events(self, response: streams_service.ListEventsResponse) -> streams_service.ListEventsResponse: + """Post-rpc interceptor for list_events + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_series(self, request: streams_service.ListSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_series(self, response: streams_service.ListSeriesResponse) -> streams_service.ListSeriesResponse: + """Post-rpc interceptor for list_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_streams(self, request: streams_service.ListStreamsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListStreamsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_streams + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_streams(self, response: streams_service.ListStreamsResponse) -> streams_service.ListStreamsResponse: + """Post-rpc interceptor for list_streams + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_materialize_channel(self, request: streams_service.MaterializeChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.MaterializeChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for materialize_channel + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_materialize_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for materialize_channel + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_cluster(self, request: streams_service.UpdateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_event(self, request: streams_service.UpdateEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_event(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_series(self, request: streams_service.UpdateSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_series(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_stream(self, request: streams_service.UpdateStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_stream(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class StreamsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: StreamsServiceRestInterceptor + + +class StreamsServiceRestTransport(StreamsServiceTransport): + """REST backend transport for StreamsService. + + Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[StreamsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or StreamsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create cluster method over HTTP. + + Args: + request (~.streams_service.CreateClusterRequest): + The request object. Message for creating a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/clusters', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_cluster(request, metadata) + pb_request = streams_service.CreateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_cluster(resp) + return resp + + class _CreateEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "eventId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create event method over HTTP. + + Args: + request (~.streams_service.CreateEventRequest): + The request object. Message for creating a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/events', + 'body': 'event', + }, + ] + request, metadata = self._interceptor.pre_create_event(request, metadata) + pb_request = streams_service.CreateEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_event(resp) + return resp + + class _CreateSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "seriesId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create series method over HTTP. + + Args: + request (~.streams_service.CreateSeriesRequest): + The request object. Message for creating a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/series', + 'body': 'series', + }, + ] + request, metadata = self._interceptor.pre_create_series(request, metadata) + pb_request = streams_service.CreateSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_series(resp) + return resp + + class _CreateStream(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "streamId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create stream method over HTTP. + + Args: + request (~.streams_service.CreateStreamRequest): + The request object. Message for creating a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/streams', + 'body': 'stream', + }, + ] + request, metadata = self._interceptor.pre_create_stream(request, metadata) + pb_request = streams_service.CreateStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_stream(resp) + return resp + + class _DeleteCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete cluster method over HTTP. + + Args: + request (~.streams_service.DeleteClusterRequest): + The request object. Message for deleting a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_cluster(request, metadata) + pb_request = streams_service.DeleteClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_cluster(resp) + return resp + + class _DeleteEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete event method over HTTP. + + Args: + request (~.streams_service.DeleteEventRequest): + The request object. Message for deleting a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/events/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_event(request, metadata) + pb_request = streams_service.DeleteEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_event(resp) + return resp + + class _DeleteSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete series method over HTTP. + + Args: + request (~.streams_service.DeleteSeriesRequest): + The request object. Message for deleting a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/series/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_series(request, metadata) + pb_request = streams_service.DeleteSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_series(resp) + return resp + + class _DeleteStream(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete stream method over HTTP. + + Args: + request (~.streams_service.DeleteStreamRequest): + The request object. Message for deleting a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/streams/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_stream(request, metadata) + pb_request = streams_service.DeleteStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_stream(resp) + return resp + + class _GenerateStreamHlsToken(StreamsServiceRestStub): + def __hash__(self): + return hash("GenerateStreamHlsToken") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GenerateStreamHlsTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.GenerateStreamHlsTokenResponse: + r"""Call the generate stream hls token method over HTTP. + + Args: + request (~.streams_service.GenerateStreamHlsTokenRequest): + The request object. Request message for getting the auth + token to access the stream HLS contents. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.GenerateStreamHlsTokenResponse: + Response message for + GenerateStreamHlsToken. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{stream=projects/*/locations/*/clusters/*/streams/*}:generateStreamHlsToken', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_stream_hls_token(request, metadata) + pb_request = streams_service.GenerateStreamHlsTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.GenerateStreamHlsTokenResponse() + pb_resp = streams_service.GenerateStreamHlsTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_stream_hls_token(resp) + return resp + + class _GetCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("GetCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> common.Cluster: + r"""Call the get cluster method over HTTP. + + Args: + request (~.streams_service.GetClusterRequest): + The request object. Message for getting a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.Cluster: + Message describing the Cluster + object. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_cluster(request, metadata) + pb_request = streams_service.GetClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.Cluster() + pb_resp = common.Cluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_cluster(resp) + return resp + + class _GetEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("GetEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_resources.Event: + r"""Call the get event method over HTTP. + + Args: + request (~.streams_service.GetEventRequest): + The request object. Message for getting a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_resources.Event: + Message describing the Event object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/events/*}', + }, + ] + request, metadata = self._interceptor.pre_get_event(request, metadata) + pb_request = streams_service.GetEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_resources.Event() + pb_resp = streams_resources.Event.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_event(resp) + return resp + + class _GetSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("GetSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_resources.Series: + r"""Call the get series method over HTTP. + + Args: + request (~.streams_service.GetSeriesRequest): + The request object. Message for getting a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_resources.Series: + Message describing the Series object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/series/*}', + }, + ] + request, metadata = self._interceptor.pre_get_series(request, metadata) + pb_request = streams_service.GetSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_resources.Series() + pb_resp = streams_resources.Series.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_series(resp) + return resp + + class _GetStream(StreamsServiceRestStub): + def __hash__(self): + return hash("GetStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_resources.Stream: + r"""Call the get stream method over HTTP. + + Args: + request (~.streams_service.GetStreamRequest): + The request object. Message for getting a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_resources.Stream: + Message describing the Stream object. + The Stream and the Event resources are + many to many; i.e., each Stream resource + can associate to many Event resources + and each Event resource can associate to + many Stream resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/streams/*}', + }, + ] + request, metadata = self._interceptor.pre_get_stream(request, metadata) + pb_request = streams_service.GetStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_resources.Stream() + pb_resp = streams_resources.Stream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_stream(resp) + return resp + + class _GetStreamThumbnail(StreamsServiceRestStub): + def __hash__(self): + return hash("GetStreamThumbnail") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetStreamThumbnailRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the get stream thumbnail method over HTTP. + + Args: + request (~.streams_service.GetStreamThumbnailRequest): + The request object. Message for getting the thumbnail of + a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{stream=projects/*/locations/*/clusters/*/streams/*}:getThumbnail', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_stream_thumbnail(request, metadata) + pb_request = streams_service.GetStreamThumbnailRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_stream_thumbnail(resp) + return resp + + class _ListClusters(StreamsServiceRestStub): + def __hash__(self): + return hash("ListClusters") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListClustersResponse: + r"""Call the list clusters method over HTTP. + + Args: + request (~.streams_service.ListClustersRequest): + The request object. Message for requesting list of + Clusters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListClustersResponse: + Message for response to listing + Clusters. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/clusters', + }, + ] + request, metadata = self._interceptor.pre_list_clusters(request, metadata) + pb_request = streams_service.ListClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListClustersResponse() + pb_resp = streams_service.ListClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_clusters(resp) + return resp + + class _ListEvents(StreamsServiceRestStub): + def __hash__(self): + return hash("ListEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListEventsResponse: + r"""Call the list events method over HTTP. + + Args: + request (~.streams_service.ListEventsRequest): + The request object. Message for requesting list of + Events. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListEventsResponse: + Message for response to listing + Events. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/events', + }, + ] + request, metadata = self._interceptor.pre_list_events(request, metadata) + pb_request = streams_service.ListEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListEventsResponse() + pb_resp = streams_service.ListEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_events(resp) + return resp + + class _ListSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("ListSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListSeriesResponse: + r"""Call the list series method over HTTP. + + Args: + request (~.streams_service.ListSeriesRequest): + The request object. Message for requesting list of + Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListSeriesResponse: + Message for response to listing + Series. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/series', + }, + ] + request, metadata = self._interceptor.pre_list_series(request, metadata) + pb_request = streams_service.ListSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListSeriesResponse() + pb_resp = streams_service.ListSeriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_series(resp) + return resp + + class _ListStreams(StreamsServiceRestStub): + def __hash__(self): + return hash("ListStreams") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListStreamsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListStreamsResponse: + r"""Call the list streams method over HTTP. + + Args: + request (~.streams_service.ListStreamsRequest): + The request object. Message for requesting list of + Streams. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListStreamsResponse: + Message for response to listing + Streams. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/streams', + }, + ] + request, metadata = self._interceptor.pre_list_streams(request, metadata) + pb_request = streams_service.ListStreamsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListStreamsResponse() + pb_resp = streams_service.ListStreamsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_streams(resp) + return resp + + class _MaterializeChannel(StreamsServiceRestStub): + def __hash__(self): + return hash("MaterializeChannel") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "channelId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.MaterializeChannelRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the materialize channel method over HTTP. + + Args: + request (~.streams_service.MaterializeChannelRequest): + The request object. Message for materializing a channel. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/channels', + 'body': 'channel', + }, + ] + request, metadata = self._interceptor.pre_materialize_channel(request, metadata) + pb_request = streams_service.MaterializeChannelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_materialize_channel(resp) + return resp + + class _UpdateCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update cluster method over HTTP. + + Args: + request (~.streams_service.UpdateClusterRequest): + The request object. Message for updating a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{cluster.name=projects/*/locations/*/clusters/*}', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_update_cluster(request, metadata) + pb_request = streams_service.UpdateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_cluster(resp) + return resp + + class _UpdateEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update event method over HTTP. + + Args: + request (~.streams_service.UpdateEventRequest): + The request object. Message for updating a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{event.name=projects/*/locations/*/clusters/*/events/*}', + 'body': 'event', + }, + ] + request, metadata = self._interceptor.pre_update_event(request, metadata) + pb_request = streams_service.UpdateEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_event(resp) + return resp + + class _UpdateSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update series method over HTTP. + + Args: + request (~.streams_service.UpdateSeriesRequest): + The request object. Message for updating a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{series.name=projects/*/locations/*/clusters/*/series/*}', + 'body': 'series', + }, + ] + request, metadata = self._interceptor.pre_update_series(request, metadata) + pb_request = streams_service.UpdateSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_series(resp) + return resp + + class _UpdateStream(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update stream method over HTTP. + + Args: + request (~.streams_service.UpdateStreamRequest): + The request object. Message for updating a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{stream.name=projects/*/locations/*/clusters/*/streams/*}', + 'body': 'stream', + }, + ] + request, metadata = self._interceptor.pre_update_stream(request, metadata) + pb_request = streams_service.UpdateStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_stream(resp) + return resp + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + streams_service.GenerateStreamHlsTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateStreamHlsToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + common.Cluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + streams_resources.Event]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + streams_resources.Series]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + streams_resources.Stream]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_stream_thumbnail(self) -> Callable[ + [streams_service.GetStreamThumbnailRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetStreamThumbnail(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + streams_service.ListClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + streams_service.ListEventsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + streams_service.ListSeriesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + streams_service.ListStreamsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListStreams(self._session, self._host, self._interceptor) # type: ignore + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._MaterializeChannel(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'StreamsServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/__init__.py new file mode 100644 index 000000000000..3e3bcdf7cf2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 WarehouseClient +from .async_client import WarehouseAsyncClient + +__all__ = ( + 'WarehouseClient', + 'WarehouseAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/async_client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/async_client.py new file mode 100644 index 000000000000..f0558abde6fe --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/async_client.py @@ -0,0 +1,7516 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.warehouse import pagers +from google.cloud.visionai_v1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WarehouseTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WarehouseGrpcAsyncIOTransport +from .client import WarehouseClient + + +class WarehouseAsyncClient: + """Service that manages media content + metadata for streaming.""" + + _client: WarehouseClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WarehouseClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WarehouseClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WarehouseClient._DEFAULT_UNIVERSE + + annotation_path = staticmethod(WarehouseClient.annotation_path) + parse_annotation_path = staticmethod(WarehouseClient.parse_annotation_path) + asset_path = staticmethod(WarehouseClient.asset_path) + parse_asset_path = staticmethod(WarehouseClient.parse_asset_path) + collection_path = staticmethod(WarehouseClient.collection_path) + parse_collection_path = staticmethod(WarehouseClient.parse_collection_path) + corpus_path = staticmethod(WarehouseClient.corpus_path) + parse_corpus_path = staticmethod(WarehouseClient.parse_corpus_path) + data_schema_path = staticmethod(WarehouseClient.data_schema_path) + parse_data_schema_path = staticmethod(WarehouseClient.parse_data_schema_path) + index_path = staticmethod(WarehouseClient.index_path) + parse_index_path = staticmethod(WarehouseClient.parse_index_path) + index_endpoint_path = staticmethod(WarehouseClient.index_endpoint_path) + parse_index_endpoint_path = staticmethod(WarehouseClient.parse_index_endpoint_path) + search_config_path = staticmethod(WarehouseClient.search_config_path) + parse_search_config_path = staticmethod(WarehouseClient.parse_search_config_path) + search_hypernym_path = staticmethod(WarehouseClient.search_hypernym_path) + parse_search_hypernym_path = staticmethod(WarehouseClient.parse_search_hypernym_path) + common_billing_account_path = staticmethod(WarehouseClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WarehouseClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WarehouseClient.common_folder_path) + parse_common_folder_path = staticmethod(WarehouseClient.parse_common_folder_path) + common_organization_path = staticmethod(WarehouseClient.common_organization_path) + parse_common_organization_path = staticmethod(WarehouseClient.parse_common_organization_path) + common_project_path = staticmethod(WarehouseClient.common_project_path) + parse_common_project_path = staticmethod(WarehouseClient.parse_common_project_path) + common_location_path = staticmethod(WarehouseClient.common_location_path) + parse_common_location_path = staticmethod(WarehouseClient.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: + WarehouseAsyncClient: The constructed client. + """ + return WarehouseClient.from_service_account_info.__func__(WarehouseAsyncClient, 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: + WarehouseAsyncClient: The constructed client. + """ + return WarehouseClient.from_service_account_file.__func__(WarehouseAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return WarehouseClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WarehouseTransport: + """Returns the transport used by the client instance. + + Returns: + WarehouseTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(WarehouseClient).get_transport_class, type(WarehouseClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WarehouseTransport, Callable[..., WarehouseTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the warehouse async 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 (Optional[Union[str,WarehouseTransport,Callable[..., WarehouseTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the WarehouseTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = WarehouseClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_asset(self, + request: Optional[Union[warehouse.CreateAssetRequest, dict]] = None, + *, + parent: Optional[str] = None, + asset: Optional[warehouse.Asset] = None, + asset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Creates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateAssetRequest, dict]]): + The request object. Request message for + CreateAssetRequest. + parent (:class:`str`): + Required. The parent resource where this asset will be + created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset (:class:`google.cloud.visionai_v1.types.Asset`): + Required. The asset to create. + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_id (:class:`str`): + Optional. The ID to use for the asset, which will become + the final component of the asset's resource name if user + choose to specify. Otherwise, asset id will be generated + by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``asset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, asset, asset_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAssetRequest): + request = warehouse.CreateAssetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if asset is not None: + request.asset = asset + if asset_id is not None: + request.asset_id = asset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_asset(self, + request: Optional[Union[warehouse.UpdateAssetRequest, dict]] = None, + *, + asset: Optional[warehouse.Asset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Updates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAssetRequest( + ) + + # Make the request + response = await client.update_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateAssetRequest, dict]]): + The request object. Request message for UpdateAsset. + asset (:class:`google.cloud.visionai_v1.types.Asset`): + Required. The asset to update. + + The asset's ``name`` field is used to identify the asset + to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([asset, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAssetRequest): + request = warehouse.UpdateAssetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if asset is not None: + request.asset = asset + 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._client._transport._wrapped_methods[self._client._transport.update_asset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("asset.name", request.asset.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_asset(self, + request: Optional[Union[warehouse.GetAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Reads an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetAssetRequest, dict]]): + The request object. Request message for GetAsset. + name (:class:`str`): + Required. The name of the asset to retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAssetRequest): + request = warehouse.GetAssetRequest(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._client._transport._wrapped_methods[self._client._transport.get_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[warehouse.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an list of assets inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListAssetsRequest, dict]]): + The request object. Request message for ListAssets. + parent (:class:`str`): + Required. The parent, which owns this collection of + assets. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListAssetsAsyncPager: + Response message for ListAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAssetsRequest): + request = warehouse.ListAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_assets] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_asset(self, + request: Optional[Union[warehouse.DeleteAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteAssetRequest, dict]]): + The request object. Request message for DeleteAsset. + name (:class:`str`): + Required. The name of the asset to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAssetRequest): + request = warehouse.DeleteAssetRequest(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._client._transport._wrapped_methods[self._client._transport.delete_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteAssetMetadata, + ) + + # Done; return the response. + return response + + async def upload_asset(self, + request: Optional[Union[warehouse.UploadAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Upload asset by specifing the asset Cloud Storage + uri. For video warehouse, it requires users who call + this API have read access to the cloud storage file. + Once it is uploaded, it can be retrieved by + GenerateRetrievalUrl API which by default, only can + retrieve cloud storage files from the same project of + the warehouse. To allow retrieval cloud storage files + that are in a separate project, it requires to find the + vision ai service account (Go to IAM, check checkbox to + show "Include Google-provided role grants", search for + "Cloud Vision AI Service Agent") and grant the read + access of the cloud storage files to that service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_upload_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UploadAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.upload_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UploadAssetRequest, dict]]): + The request object. Request message for UploadAsset. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UploadAssetResponse` + Response message for UploadAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UploadAssetRequest): + request = warehouse.UploadAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.upload_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.UploadAssetResponse, + metadata_type=warehouse.UploadAssetMetadata, + ) + + # Done; return the response. + return response + + async def generate_retrieval_url(self, + request: Optional[Union[warehouse.GenerateRetrievalUrlRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.GenerateRetrievalUrlResponse: + r"""Generates a signed url for downloading the asset. + For video warehouse, please see comment of UploadAsset + about how to allow retrieval of cloud storage files in a + different project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_generate_retrieval_url(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateRetrievalUrlRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_retrieval_url(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GenerateRetrievalUrlRequest, dict]]): + The request object. Request message for + GenerateRetrievalUrl API. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.GenerateRetrievalUrlResponse: + Response message for + GenerateRetrievalUrl API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GenerateRetrievalUrlRequest): + request = warehouse.GenerateRetrievalUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_retrieval_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_asset(self, + request: Optional[Union[warehouse.AnalyzeAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Analyze asset to power search capability. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_analyze_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.AnalyzeAssetRequest, dict]]): + The request object. Request message for AnalyzeAsset. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.AnalyzeAssetResponse` + Response message for AnalyzeAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.AnalyzeAssetRequest): + request = warehouse.AnalyzeAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.AnalyzeAssetResponse, + metadata_type=warehouse.AnalyzeAssetMetadata, + ) + + # Done; return the response. + return response + + async def index_asset(self, + request: Optional[Union[warehouse.IndexAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Index one asset for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_index_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.IndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.index_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.IndexAssetRequest, dict]]): + The request object. Request message for IndexAsset. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.IndexAssetResponse` + Response message for IndexAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.IndexAssetRequest): + request = warehouse.IndexAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.index_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.IndexAssetResponse, + metadata_type=warehouse.IndexAssetMetadata, + ) + + # Done; return the response. + return response + + async def remove_index_asset(self, + request: Optional[Union[warehouse.RemoveIndexAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove one asset's index data for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_remove_index_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveIndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_index_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.RemoveIndexAssetRequest, dict]]): + The request object. Request message for RemoveIndexAsset. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.RemoveIndexAssetResponse` + Response message for RemoveIndexAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.RemoveIndexAssetRequest): + request = warehouse.RemoveIndexAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.remove_index_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.RemoveIndexAssetResponse, + metadata_type=warehouse.RemoveIndexAssetMetadata, + ) + + # Done; return the response. + return response + + async def view_indexed_assets(self, + request: Optional[Union[warehouse.ViewIndexedAssetsRequest, dict]] = None, + *, + index: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ViewIndexedAssetsAsyncPager: + r"""Lists assets inside an index. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_view_indexed_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ViewIndexedAssetsRequest( + index="index_value", + ) + + # Make the request + page_result = client.view_indexed_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ViewIndexedAssetsRequest, dict]]): + The request object. Request message for + ViewIndexedAssets. + index (:class:`str`): + Required. The index that owns this collection of assets. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + + This corresponds to the ``index`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ViewIndexedAssetsAsyncPager: + Response message for + ViewIndexedAssets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([index]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ViewIndexedAssetsRequest): + request = warehouse.ViewIndexedAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if index is not None: + request.index = index + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.view_indexed_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index", request.index), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ViewIndexedAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_index(self, + request: Optional[Union[warehouse.CreateIndexRequest, dict]] = None, + *, + parent: Optional[str] = None, + index: Optional[warehouse.Index] = None, + index_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an Index under the corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.CreateIndexRequest( + parent="parent_value", + index=index, + ) + + # Make the request + operation = client.create_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateIndexRequest, dict]]): + The request object. Message for creating an Index. + parent (:class:`str`): + Required. Value for the parent. The resource name of the + Corpus under which this index is created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index (:class:`google.cloud.visionai_v1.types.Index`): + Required. The index being created. + This corresponds to the ``index`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index_id (:class:`str`): + Optional. The ID for the index. This will become the + final resource name for the index. If the user does not + specify this value, it will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``index_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Index` An Index is a resource in Corpus. It contains an indexed version of the + assets and annotations. When deployed to an endpoint, + it will allow users to search the Index. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, index, index_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateIndexRequest): + request = warehouse.CreateIndexRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if index is not None: + request.index = index + if index_id is not None: + request.index_id = index_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_index] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.Index, + metadata_type=warehouse.CreateIndexMetadata, + ) + + # Done; return the response. + return response + + async def update_index(self, + request: Optional[Union[warehouse.UpdateIndexRequest, dict]] = None, + *, + index: Optional[warehouse.Index] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an Index under the corpus. Users can perform a + metadata-only update or trigger a full index rebuild with + different update_mask values. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.UpdateIndexRequest( + index=index, + ) + + # Make the request + operation = client.update_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateIndexRequest, dict]]): + The request object. Request message for UpdateIndex. + index (:class:`google.cloud.visionai_v1.types.Index`): + Required. The resource being updated. + This corresponds to the ``index`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Index resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field of the resource + will be overwritten if it is in the mask. Empty field + mask is not allowed. If the mask is "*", it triggers a + full update of the index, and also a whole rebuild of + index data. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Index` An Index is a resource in Corpus. It contains an indexed version of the + assets and annotations. When deployed to an endpoint, + it will allow users to search the Index. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([index, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateIndexRequest): + request = warehouse.UpdateIndexRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if index is not None: + request.index = index + 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._client._transport._wrapped_methods[self._client._transport.update_index] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index.name", request.index.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.Index, + metadata_type=warehouse.UpdateIndexMetadata, + ) + + # Done; return the response. + return response + + async def get_index(self, + request: Optional[Union[warehouse.GetIndexRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Index: + r"""Gets the details of a single Index under a Corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexRequest( + name="name_value", + ) + + # Make the request + response = await client.get_index(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetIndexRequest, dict]]): + The request object. Request message for getting an Index. + name (:class:`str`): + Required. Name of the Index resource. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Index: + An Index is a resource in Corpus. It + contains an indexed version of the + assets and annotations. When deployed to + an endpoint, it will allow users to + search the Index. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetIndexRequest): + request = warehouse.GetIndexRequest(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._client._transport._wrapped_methods[self._client._transport.get_index] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_indexes(self, + request: Optional[Union[warehouse.ListIndexesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIndexesAsyncPager: + r"""List all Indexes in a given Corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_indexes(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_indexes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListIndexesRequest, dict]]): + The request object. Request message for listing Indexes. + parent (:class:`str`): + Required. The parent corpus that owns this collection of + indexes. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListIndexesAsyncPager: + Response message for ListIndexes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListIndexesRequest): + request = warehouse.ListIndexesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_indexes] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListIndexesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_index(self, + request: Optional[Union[warehouse.DeleteIndexRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single Index. In order to delete an index, + the caller must make sure that it is not deployed to any + index endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteIndexRequest, dict]]): + The request object. Request message for DeleteIndex. + name (:class:`str`): + Required. The name of the index to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteIndexRequest): + request = warehouse.DeleteIndexRequest(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._client._transport._wrapped_methods[self._client._transport.delete_index] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteIndexMetadata, + ) + + # Done; return the response. + return response + + async def create_corpus(self, + request: Optional[Union[warehouse.CreateCorpusRequest, dict]] = None, + *, + parent: Optional[str] = None, + corpus: Optional[warehouse.Corpus] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a corpus inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateCorpusRequest, dict]]): + The request object. Request message of CreateCorpus API. + parent (:class:`str`): + Required. Form: + ``projects/{project_number}/locations/{location_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + corpus (:class:`google.cloud.visionai_v1.types.Corpus`): + Required. The corpus to be created. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Corpus` Corpus is a set of media contents for management. + Within a corpus, media shares the same data schema. + Search is also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, corpus]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateCorpusRequest): + request = warehouse.CreateCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if corpus is not None: + request.corpus = corpus + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.Corpus, + metadata_type=warehouse.CreateCorpusMetadata, + ) + + # Done; return the response. + return response + + async def get_corpus(self, + request: Optional[Union[warehouse.GetCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Gets corpus details inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetCorpusRequest, dict]]): + The request object. Request message for GetCorpus. + name (:class:`str`): + Required. The resource name of the + corpus to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Corpus: + Corpus is a set of media contents for + management. Within a corpus, media + shares the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetCorpusRequest): + request = warehouse.GetCorpusRequest(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._client._transport._wrapped_methods[self._client._transport.get_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_corpus(self, + request: Optional[Union[warehouse.UpdateCorpusRequest, dict]] = None, + *, + corpus: Optional[warehouse.Corpus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Updates a corpus in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = await client.update_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateCorpusRequest, dict]]): + The request object. Request message for UpdateCorpus. + corpus (:class:`google.cloud.visionai_v1.types.Corpus`): + Required. The corpus which replaces + the resource on the server. + + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Corpus: + Corpus is a set of media contents for + management. Within a corpus, media + shares the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateCorpusRequest): + request = warehouse.UpdateCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + 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._client._transport._wrapped_methods[self._client._transport.update_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus.name", request.corpus.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_corpora(self, + request: Optional[Union[warehouse.ListCorporaRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCorporaAsyncPager: + r"""Lists all corpora in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_corpora(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListCorporaRequest, dict]]): + The request object. Request message for ListCorpora. + parent (:class:`str`): + Required. The resource name of the + project from which to list corpora. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListCorporaAsyncPager: + Response message for ListCorpora. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListCorporaRequest): + request = warehouse.ListCorporaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_corpora] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListCorporaAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_corpus(self, + request: Optional[Union[warehouse.DeleteCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a corpus only if its empty. + Returns empty response. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + await client.delete_corpus(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteCorpusRequest, dict]]): + The request object. Request message for DeleteCorpus. + name (:class:`str`): + Required. The resource name of the + corpus to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteCorpusRequest): + request = warehouse.DeleteCorpusRequest(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._client._transport._wrapped_methods[self._client._transport.delete_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def analyze_corpus(self, + request: Optional[Union[warehouse.AnalyzeCorpusRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Analyzes a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_analyze_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeCorpusRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_corpus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.AnalyzeCorpusRequest, dict]]): + The request object. Request message for AnalyzeCorpus. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.AnalyzeCorpusResponse` + The response message for AnalyzeCorpus LRO. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.AnalyzeCorpusRequest): + request = warehouse.AnalyzeCorpusRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.AnalyzeCorpusResponse, + metadata_type=warehouse.AnalyzeCorpusMetadata, + ) + + # Done; return the response. + return response + + async def create_data_schema(self, + request: Optional[Union[warehouse.CreateDataSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_schema: Optional[warehouse.DataSchema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Creates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = await client.create_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateDataSchemaRequest, dict]]): + The request object. Request message for CreateDataSchema. + parent (:class:`str`): + Required. The parent resource where this data schema + will be created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_schema (:class:`google.cloud.visionai_v1.types.DataSchema`): + Required. The data schema to create. + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_schema]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateDataSchemaRequest): + request = warehouse.CreateDataSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_schema is not None: + request.data_schema = data_schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_data_schema(self, + request: Optional[Union[warehouse.UpdateDataSchemaRequest, dict]] = None, + *, + data_schema: Optional[warehouse.DataSchema] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Updates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = await client.update_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateDataSchemaRequest, dict]]): + The request object. Request message for UpdateDataSchema. + data_schema (:class:`google.cloud.visionai_v1.types.DataSchema`): + Required. The data schema's ``name`` field is used to + identify the data schema to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`` + + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_schema, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateDataSchemaRequest): + request = warehouse.UpdateDataSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_schema is not None: + request.data_schema = data_schema + 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._client._transport._wrapped_methods[self._client._transport.update_data_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_schema.name", request.data_schema.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_schema(self, + request: Optional[Union[warehouse.GetDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Gets data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetDataSchemaRequest, dict]]): + The request object. Request message for GetDataSchema. + name (:class:`str`): + Required. The name of the data schema to retrieve. + Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetDataSchemaRequest): + request = warehouse.GetDataSchemaRequest(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._client._transport._wrapped_methods[self._client._transport.get_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_data_schema(self, + request: Optional[Union[warehouse.DeleteDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_schema(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteDataSchemaRequest, dict]]): + The request object. Request message for DeleteDataSchema. + name (:class:`str`): + Required. The name of the data schema to delete. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteDataSchemaRequest): + request = warehouse.DeleteDataSchemaRequest(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._client._transport._wrapped_methods[self._client._transport.delete_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_data_schemas(self, + request: Optional[Union[warehouse.ListDataSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataSchemasAsyncPager: + r"""Lists a list of data schemas inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_data_schemas(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListDataSchemasRequest, dict]]): + The request object. Request message for ListDataSchemas. + parent (:class:`str`): + Required. The parent, which owns this collection of data + schemas. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListDataSchemasAsyncPager: + Response message for ListDataSchemas. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListDataSchemasRequest): + request = warehouse.ListDataSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_data_schemas] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListDataSchemasAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_annotation(self, + request: Optional[Union[warehouse.CreateAnnotationRequest, dict]] = None, + *, + parent: Optional[str] = None, + annotation: Optional[warehouse.Annotation] = None, + annotation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Creates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateAnnotationRequest, dict]]): + The request object. Request message for CreateAnnotation. + parent (:class:`str`): + Required. The parent resource where this annotation will + be created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation (:class:`google.cloud.visionai_v1.types.Annotation`): + Required. The annotation to create. + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation_id (:class:`str`): + Optional. The ID to use for the annotation, which will + become the final component of the annotation's resource + name if user choose to specify. Otherwise, annotation id + will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``annotation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, annotation, annotation_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAnnotationRequest): + request = warehouse.CreateAnnotationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if annotation is not None: + request.annotation = annotation + if annotation_id is not None: + request.annotation_id = annotation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_annotation(self, + request: Optional[Union[warehouse.GetAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Reads annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetAnnotationRequest, dict]]): + The request object. Request message for GetAnnotation + API. + name (:class:`str`): + Required. The name of the annotation to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAnnotationRequest): + request = warehouse.GetAnnotationRequest(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._client._transport._wrapped_methods[self._client._transport.get_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_annotations(self, + request: Optional[Union[warehouse.ListAnnotationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotationsAsyncPager: + r"""Lists a list of annotations inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_annotations(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListAnnotationsRequest, dict]]): + The request object. Request message for GetAnnotation + API. + parent (:class:`str`): + The parent, which owns this collection of annotations. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListAnnotationsAsyncPager: + Request message for ListAnnotations + API. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAnnotationsRequest): + request = warehouse.ListAnnotationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_annotations] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAnnotationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_annotation(self, + request: Optional[Union[warehouse.UpdateAnnotationRequest, dict]] = None, + *, + annotation: Optional[warehouse.Annotation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Updates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnnotationRequest( + ) + + # Make the request + response = await client.update_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateAnnotationRequest, dict]]): + The request object. Request message for UpdateAnnotation + API. + annotation (:class:`google.cloud.visionai_v1.types.Annotation`): + Required. The annotation to update. The annotation's + ``name`` field is used to identify the annotation to be + updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([annotation, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAnnotationRequest): + request = warehouse.UpdateAnnotationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if annotation is not None: + request.annotation = annotation + 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._client._transport._wrapped_methods[self._client._transport.update_annotation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("annotation.name", request.annotation.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_annotation(self, + request: Optional[Union[warehouse.DeleteAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + await client.delete_annotation(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteAnnotationRequest, dict]]): + The request object. Request message for DeleteAnnotation + API. + name (:class:`str`): + Required. The name of the annotation to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAnnotationRequest): + request = warehouse.DeleteAnnotationRequest(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._client._transport._wrapped_methods[self._client._transport.delete_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def ingest_asset(self, + requests: Optional[AsyncIterator[warehouse.IngestAssetRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[warehouse.IngestAssetResponse]]: + r"""Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_ingest_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + config = visionai_v1.Config() + config.asset = "asset_value" + + request = visionai_v1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.ingest_asset(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1.types.IngestAssetRequest`]): + The request object AsyncIterator. Request message for IngestAsset API. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1.types.IngestAssetResponse]: + Response message for IngestAsset API. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.ingest_asset] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def clip_asset(self, + request: Optional[Union[warehouse.ClipAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.ClipAssetResponse: + r"""Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_clip_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.clip_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ClipAssetRequest, dict]]): + The request object. Request message for ClipAsset API. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ClipAssetResponse: + Response message for ClipAsset API. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ClipAssetRequest): + request = warehouse.ClipAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.clip_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_hls_uri(self, + request: Optional[Union[warehouse.GenerateHlsUriRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.GenerateHlsUriResponse: + r"""Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_generate_hls_uri(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_hls_uri(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GenerateHlsUriRequest, dict]]): + The request object. Request message for GenerateHlsUri + API. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.GenerateHlsUriResponse: + Response message for GenerateHlsUri + API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GenerateHlsUriRequest): + request = warehouse.GenerateHlsUriRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_hls_uri] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_assets(self, + request: Optional[Union[warehouse.ImportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports assets (images plus annotations) from a meta + file on cloud storage. Each row in the meta file is + corresponding to an image (specified by a cloud storage + uri) and its annotations. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_import_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ImportAssetsRequest( + assets_gcs_uri="assets_gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_assets(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ImportAssetsRequest, dict]]): + The request object. The request message for ImportAssets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.ImportAssetsResponse` + The response message for ImportAssets LRO. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ImportAssetsRequest): + request = warehouse.ImportAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.import_assets] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.ImportAssetsResponse, + metadata_type=warehouse.ImportAssetsMetadata, + ) + + # Done; return the response. + return response + + async def create_search_config(self, + request: Optional[Union[warehouse.CreateSearchConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_config: Optional[warehouse.SearchConfig] = None, + search_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = await client.create_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateSearchConfigRequest, dict]]): + The request object. Request message for + CreateSearchConfig. + parent (:class:`str`): + Required. The parent resource where this search + configuration will be created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config (:class:`google.cloud.visionai_v1.types.SearchConfig`): + Required. The search config to + create. + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config_id (:class:`str`): + Required. ID to use for the new search config. Will + become the final component of the SearchConfig's + resource name. This value should be up to 63 characters, + and valid characters are /[a-z][0-9]-_/. The first + character must be a letter, the last could be a letter + or a number. + + This corresponds to the ``search_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_config, search_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateSearchConfigRequest): + request = warehouse.CreateSearchConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_config is not None: + request.search_config = search_config + if search_config_id is not None: + request.search_config_id = search_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_search_config(self, + request: Optional[Union[warehouse.UpdateSearchConfigRequest, dict]] = None, + *, + search_config: Optional[warehouse.SearchConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchConfigRequest( + ) + + # Make the request + response = await client.update_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateSearchConfigRequest, dict]]): + The request object. Request message for + UpdateSearchConfig. + search_config (:class:`google.cloud.visionai_v1.types.SearchConfig`): + Required. The search configuration to update. + + The search configuration's ``name`` field is used to + identify the resource to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If + left unset, all field paths will be + updated/overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_config, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateSearchConfigRequest): + request = warehouse.UpdateSearchConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_config is not None: + request.search_config = search_config + 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._client._transport._wrapped_methods[self._client._transport.update_search_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_config.name", request.search_config.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_search_config(self, + request: Optional[Union[warehouse.GetSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Gets a search configuration inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetSearchConfigRequest, dict]]): + The request object. Request message for GetSearchConfig. + name (:class:`str`): + Required. The name of the search configuration to + retrieve. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetSearchConfigRequest): + request = warehouse.GetSearchConfigRequest(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._client._transport._wrapped_methods[self._client._transport.get_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_search_config(self, + request: Optional[Union[warehouse.DeleteSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_search_config(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteSearchConfigRequest, dict]]): + The request object. Request message for + DeleteSearchConfig. + name (:class:`str`): + Required. The name of the search configuration to + delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteSearchConfigRequest): + request = warehouse.DeleteSearchConfigRequest(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._client._transport._wrapped_methods[self._client._transport.delete_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_search_configs(self, + request: Optional[Union[warehouse.ListSearchConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSearchConfigsAsyncPager: + r"""Lists all search configurations inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_search_configs(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListSearchConfigsRequest, dict]]): + The request object. Request message for + ListSearchConfigs. + parent (:class:`str`): + Required. The parent, which owns this collection of + search configurations. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListSearchConfigsAsyncPager: + Response message for + ListSearchConfigs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListSearchConfigsRequest): + request = warehouse.ListSearchConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_search_configs] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListSearchConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_search_hypernym(self, + request: Optional[Union[warehouse.CreateSearchHypernymRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_hypernym: Optional[warehouse.SearchHypernym] = None, + search_hypernym_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchHypernym: + r"""Creates a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchHypernymRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_search_hypernym(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateSearchHypernymRequest, dict]]): + The request object. Request message for creating + SearchHypernym. + parent (:class:`str`): + Required. The parent resource where this SearchHypernym + will be created. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_hypernym (:class:`google.cloud.visionai_v1.types.SearchHypernym`): + Required. The SearchHypernym to + create. + + This corresponds to the ``search_hypernym`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_hypernym_id (:class:`str`): + Optional. The search hypernym id. + If omitted, a random UUID will be + generated. + + This corresponds to the ``search_hypernym_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchHypernym: + Search resource: SearchHypernym. + For example, { hypernym: "vehicle" hyponyms: + ["sedan", "truck"] } This means in SMART_SEARCH mode, + searching for "vehicle" will also return results with + "sedan" or "truck" as annotations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_hypernym, search_hypernym_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateSearchHypernymRequest): + request = warehouse.CreateSearchHypernymRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_hypernym is not None: + request.search_hypernym = search_hypernym + if search_hypernym_id is not None: + request.search_hypernym_id = search_hypernym_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_search_hypernym] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_search_hypernym(self, + request: Optional[Union[warehouse.UpdateSearchHypernymRequest, dict]] = None, + *, + search_hypernym: Optional[warehouse.SearchHypernym] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchHypernym: + r"""Updates a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchHypernymRequest( + ) + + # Make the request + response = await client.update_search_hypernym(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateSearchHypernymRequest, dict]]): + The request object. Request message for updating + SearchHypernym. + search_hypernym (:class:`google.cloud.visionai_v1.types.SearchHypernym`): + Required. The SearchHypernym to update. The search + hypernym's ``name`` field is used to identify the search + hypernym to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + + This corresponds to the ``search_hypernym`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If + left unset, all field paths will be + updated/overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchHypernym: + Search resource: SearchHypernym. + For example, { hypernym: "vehicle" hyponyms: + ["sedan", "truck"] } This means in SMART_SEARCH mode, + searching for "vehicle" will also return results with + "sedan" or "truck" as annotations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_hypernym, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateSearchHypernymRequest): + request = warehouse.UpdateSearchHypernymRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_hypernym is not None: + request.search_hypernym = search_hypernym + 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._client._transport._wrapped_methods[self._client._transport.update_search_hypernym] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_hypernym.name", request.search_hypernym.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_search_hypernym(self, + request: Optional[Union[warehouse.GetSearchHypernymRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchHypernym: + r"""Gets a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchHypernymRequest( + name="name_value", + ) + + # Make the request + response = await client.get_search_hypernym(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetSearchHypernymRequest, dict]]): + The request object. Request message for getting + SearchHypernym. + name (:class:`str`): + Required. The name of the SearchHypernym to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchHypernym: + Search resource: SearchHypernym. + For example, { hypernym: "vehicle" hyponyms: + ["sedan", "truck"] } This means in SMART_SEARCH mode, + searching for "vehicle" will also return results with + "sedan" or "truck" as annotations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetSearchHypernymRequest): + request = warehouse.GetSearchHypernymRequest(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._client._transport._wrapped_methods[self._client._transport.get_search_hypernym] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_search_hypernym(self, + request: Optional[Union[warehouse.DeleteSearchHypernymRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchHypernymRequest( + name="name_value", + ) + + # Make the request + await client.delete_search_hypernym(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteSearchHypernymRequest, dict]]): + The request object. Request message for deleting + SearchHypernym. + name (:class:`str`): + Required. The name of the SearchHypernym to delete. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteSearchHypernymRequest): + request = warehouse.DeleteSearchHypernymRequest(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._client._transport._wrapped_methods[self._client._transport.delete_search_hypernym] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_search_hypernyms(self, + request: Optional[Union[warehouse.ListSearchHypernymsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSearchHypernymsAsyncPager: + r"""Lists SearchHypernyms inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_search_hypernyms(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchHypernymsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_hypernyms(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListSearchHypernymsRequest, dict]]): + The request object. Request message for listing + SearchHypernyms. + parent (:class:`str`): + Required. The parent, which owns this collection of + SearchHypernyms. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListSearchHypernymsAsyncPager: + Response message for listing + SearchHypernyms. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListSearchHypernymsRequest): + request = warehouse.ListSearchHypernymsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_search_hypernyms] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListSearchHypernymsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_assets(self, + request: Optional[Union[warehouse.SearchAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAssetsAsyncPager: + r"""Search media asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_search_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.SearchAssetsRequest, dict]]): + The request object. Request message for SearchAssets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.SearchAssetsAsyncPager: + Response message for SearchAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.SearchAssetsRequest): + request = warehouse.SearchAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus", request.corpus), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.SearchAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_index_endpoint(self, + request: Optional[Union[warehouse.SearchIndexEndpointRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchIndexEndpointAsyncPager: + r"""Search a deployed index endpoint (IMAGE corpus type + only). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_search_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + image_query = visionai_v1.ImageQuery() + image_query.input_image = b'input_image_blob' + + request = visionai_v1.SearchIndexEndpointRequest( + image_query=image_query, + index_endpoint="index_endpoint_value", + ) + + # Make the request + page_result = client.search_index_endpoint(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.SearchIndexEndpointRequest, dict]]): + The request object. Request message for + SearchIndexEndpoint. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.SearchIndexEndpointAsyncPager: + Response message for + SearchIndexEndpoint. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.SearchIndexEndpointRequest): + request = warehouse.SearchIndexEndpointRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint", request.index_endpoint), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.SearchIndexEndpointAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_index_endpoint(self, + request: Optional[Union[warehouse.CreateIndexEndpointRequest, dict]] = None, + *, + parent: Optional[str] = None, + index_endpoint: Optional[warehouse.IndexEndpoint] = None, + index_endpoint_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateIndexEndpointRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateIndexEndpointRequest, dict]]): + The request object. Request message for + CreateIndexEndpoint. + parent (:class:`str`): + Required. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index_endpoint (:class:`google.cloud.visionai_v1.types.IndexEndpoint`): + Required. The resource being created. + This corresponds to the ``index_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index_endpoint_id (:class:`str`): + Optional. The ID to use for the + IndexEndpoint, which will become the + final component of the IndexEndpoint's + resource name if the user specifies it. + Otherwise, IndexEndpoint id will be + autogenerated. + + This value should be up to 63 + characters, and valid characters are + a-z, 0-9 and dash (-). The first + character must be a letter, the last + must be a letter or a number. + + This corresponds to the ``index_endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.IndexEndpoint` + Message representing IndexEndpoint resource. Indexes are + deployed into it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, index_endpoint, index_endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateIndexEndpointRequest): + request = warehouse.CreateIndexEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if index_endpoint is not None: + request.index_endpoint = index_endpoint + if index_endpoint_id is not None: + request.index_endpoint_id = index_endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.IndexEndpoint, + metadata_type=warehouse.CreateIndexEndpointMetadata, + ) + + # Done; return the response. + return response + + async def get_index_endpoint(self, + request: Optional[Union[warehouse.GetIndexEndpointRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.IndexEndpoint: + r"""Gets an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexEndpointRequest( + name="name_value", + ) + + # Make the request + response = await client.get_index_endpoint(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetIndexEndpointRequest, dict]]): + The request object. Request message for GetIndexEndpoint. + name (:class:`str`): + Required. Name of the IndexEndpoint + resource. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.IndexEndpoint: + Message representing IndexEndpoint + resource. Indexes are deployed into it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetIndexEndpointRequest): + request = warehouse.GetIndexEndpointRequest(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._client._transport._wrapped_methods[self._client._transport.get_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_index_endpoints(self, + request: Optional[Union[warehouse.ListIndexEndpointsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIndexEndpointsAsyncPager: + r"""Lists all IndexEndpoints in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_index_endpoints(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_index_endpoints(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListIndexEndpointsRequest, dict]]): + The request object. Request message for + ListIndexEndpoints. + parent (:class:`str`): + Required. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListIndexEndpointsAsyncPager: + Response message for + ListIndexEndpoints. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListIndexEndpointsRequest): + request = warehouse.ListIndexEndpointsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_index_endpoints] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListIndexEndpointsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_index_endpoint(self, + request: Optional[Union[warehouse.UpdateIndexEndpointRequest, dict]] = None, + *, + index_endpoint: Optional[warehouse.IndexEndpoint] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateIndexEndpointRequest( + ) + + # Make the request + operation = client.update_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateIndexEndpointRequest, dict]]): + The request object. Request message for + UpdateIndexEndpoint. + index_endpoint (:class:`google.cloud.visionai_v1.types.IndexEndpoint`): + Required. The resource being updated. + This corresponds to the ``index_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the IndexEndpoint resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field of the + resource will be overwritten if it is in the mask. Empty + field mask is not allowed. If the mask is "*", then this + is a full replacement of the resource. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.IndexEndpoint` + Message representing IndexEndpoint resource. Indexes are + deployed into it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([index_endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateIndexEndpointRequest): + request = warehouse.UpdateIndexEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if index_endpoint is not None: + request.index_endpoint = index_endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint.name", request.index_endpoint.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.IndexEndpoint, + metadata_type=warehouse.UpdateIndexEndpointMetadata, + ) + + # Done; return the response. + return response + + async def delete_index_endpoint(self, + request: Optional[Union[warehouse.DeleteIndexEndpointRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexEndpointRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteIndexEndpointRequest, dict]]): + The request object. Request message for + DeleteIndexEndpoint. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteIndexEndpointRequest): + request = warehouse.DeleteIndexEndpointRequest(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._client._transport._wrapped_methods[self._client._transport.delete_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteIndexEndpointMetadata, + ) + + # Done; return the response. + return response + + async def deploy_index(self, + request: Optional[Union[warehouse.DeployIndexRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys an Index to IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_deploy_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + deployed_index = visionai_v1.DeployedIndex() + deployed_index.index = "index_value" + + request = visionai_v1.DeployIndexRequest( + index_endpoint="index_endpoint_value", + deployed_index=deployed_index, + ) + + # Make the request + operation = client.deploy_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeployIndexRequest, dict]]): + The request object. Request message for DeployIndex. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.DeployIndexResponse` + DeployIndex response once the operation is done. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeployIndexRequest): + request = warehouse.DeployIndexRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.deploy_index] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint", request.index_endpoint), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.DeployIndexResponse, + metadata_type=warehouse.DeployIndexMetadata, + ) + + # Done; return the response. + return response + + async def undeploy_index(self, + request: Optional[Union[warehouse.UndeployIndexRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Undeploys an Index from IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_undeploy_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployIndexRequest( + index_endpoint="index_endpoint_value", + ) + + # Make the request + operation = client.undeploy_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UndeployIndexRequest, dict]]): + The request object. Request message for + UndeployIndexEndpoint. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UndeployIndexResponse` + UndeployIndex response once the operation is done. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UndeployIndexRequest): + request = warehouse.UndeployIndexRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.undeploy_index] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint", request.index_endpoint), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.UndeployIndexResponse, + metadata_type=warehouse.UndeployIndexMetadata, + ) + + # Done; return the response. + return response + + async def create_collection(self, + request: Optional[Union[warehouse.CreateCollectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + collection: Optional[warehouse.Collection] = None, + collection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_create_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateCollectionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_collection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.CreateCollectionRequest, dict]]): + The request object. Request message for CreateCollection. + parent (:class:`str`): + Required. The parent resource where this collection will + be created. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + collection (:class:`google.cloud.visionai_v1.types.Collection`): + Required. The collection resource to + be created. + + This corresponds to the ``collection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + collection_id (:class:`str`): + Optional. The ID to use for the collection, which will + become the final component of the resource name if user + choose to specify. Otherwise, collection id will be + generated by system. + + This value should be up to 55 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``collection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Collection` A collection is a resource in a corpus. It serves as a container of + references to original resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, collection, collection_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateCollectionRequest): + request = warehouse.CreateCollectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if collection is not None: + request.collection = collection + if collection_id is not None: + request.collection_id = collection_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_collection] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.Collection, + metadata_type=warehouse.CreateCollectionMetadata, + ) + + # Done; return the response. + return response + + async def delete_collection(self, + request: Optional[Union[warehouse.DeleteCollectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_delete_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCollectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_collection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.DeleteCollectionRequest, dict]]): + The request object. Request message for + DeleteCollectionRequest. + name (:class:`str`): + Required. The name of the collection to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteCollectionRequest): + request = warehouse.DeleteCollectionRequest(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._client._transport._wrapped_methods[self._client._transport.delete_collection] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteCollectionMetadata, + ) + + # Done; return the response. + return response + + async def get_collection(self, + request: Optional[Union[warehouse.GetCollectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Collection: + r"""Gets a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_get_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetCollectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.GetCollectionRequest, dict]]): + The request object. Request message for + GetCollectionRequest. + name (:class:`str`): + Required. The name of the collection to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Collection: + A collection is a resource in a + corpus. It serves as a container of + references to original resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetCollectionRequest): + request = warehouse.GetCollectionRequest(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._client._transport._wrapped_methods[self._client._transport.get_collection] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_collection(self, + request: Optional[Union[warehouse.UpdateCollectionRequest, dict]] = None, + *, + collection: Optional[warehouse.Collection] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Collection: + r"""Updates a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_update_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateCollectionRequest( + ) + + # Make the request + response = await client.update_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.UpdateCollectionRequest, dict]]): + The request object. Request message for + UpdateCollectionRequest. + collection (:class:`google.cloud.visionai_v1.types.Collection`): + Required. The collection to update. + + The collection's ``name`` field is used to identify the + collection to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``collection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + + - Unset ``update_mask`` or set ``update_mask`` to be a + single "*" only will update all updatable fields with + the value provided in ``collection``. + - To update ``display_name`` value to empty string, set + it in the ``collection`` to empty string, and set + ``update_mask`` with "display_name". Same applies to + other updatable string fields in the ``collection``. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Collection: + A collection is a resource in a + corpus. It serves as a container of + references to original resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([collection, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateCollectionRequest): + request = warehouse.UpdateCollectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if collection is not None: + request.collection = collection + 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._client._transport._wrapped_methods[self._client._transport.update_collection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("collection.name", request.collection.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_collections(self, + request: Optional[Union[warehouse.ListCollectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCollectionsAsyncPager: + r"""Lists collections inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_list_collections(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_collections(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ListCollectionsRequest, dict]]): + The request object. Request message for ListCollections. + parent (:class:`str`): + Required. The parent corpus. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListCollectionsAsyncPager: + Response message for ListCollections. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListCollectionsRequest): + request = warehouse.ListCollectionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_collections] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListCollectionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_collection_item(self, + request: Optional[Union[warehouse.AddCollectionItemRequest, dict]] = None, + *, + item: Optional[warehouse.CollectionItem] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.AddCollectionItemResponse: + r"""Adds an item into a Collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_add_collection_item(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.AddCollectionItemRequest( + item=item, + ) + + # Make the request + response = await client.add_collection_item(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.AddCollectionItemRequest, dict]]): + The request object. Request message for + AddCollectionItem. + item (:class:`google.cloud.visionai_v1.types.CollectionItem`): + Required. The item to be added. + This corresponds to the ``item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.AddCollectionItemResponse: + Response message for + AddCollectionItem. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([item]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.AddCollectionItemRequest): + request = warehouse.AddCollectionItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if item is not None: + request.item = item + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.add_collection_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("item.collection", request.item.collection), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_collection_item(self, + request: Optional[Union[warehouse.RemoveCollectionItemRequest, dict]] = None, + *, + item: Optional[warehouse.CollectionItem] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.RemoveCollectionItemResponse: + r"""Removes an item from a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_remove_collection_item(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.RemoveCollectionItemRequest( + item=item, + ) + + # Make the request + response = await client.remove_collection_item(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.RemoveCollectionItemRequest, dict]]): + The request object. Request message for + RemoveCollectionItem. + item (:class:`google.cloud.visionai_v1.types.CollectionItem`): + Required. The item to be removed. + This corresponds to the ``item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.RemoveCollectionItemResponse: + Request message for + RemoveCollectionItem. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([item]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.RemoveCollectionItemRequest): + request = warehouse.RemoveCollectionItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if item is not None: + request.item = item + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.remove_collection_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("item.collection", request.item.collection), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def view_collection_items(self, + request: Optional[Union[warehouse.ViewCollectionItemsRequest, dict]] = None, + *, + collection: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ViewCollectionItemsAsyncPager: + r"""View items inside a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + async def sample_view_collection_items(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ViewCollectionItemsRequest( + collection="collection_value", + ) + + # Make the request + page_result = client.view_collection_items(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1.types.ViewCollectionItemsRequest, dict]]): + The request object. Request message for + ViewCollectionItems. + collection (:class:`str`): + Required. The collection to view. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``collection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ViewCollectionItemsAsyncPager: + Response message for + ViewCollectionItems. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([collection]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ViewCollectionItemsRequest): + request = warehouse.ViewCollectionItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if collection is not None: + request.collection = collection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.view_collection_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("collection", request.collection), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ViewCollectionItemsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "WarehouseAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "WarehouseAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/client.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/client.py new file mode 100644 index 000000000000..7fce62238be9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/client.py @@ -0,0 +1,7899 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.services.warehouse import pagers +from google.cloud.visionai_v1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WarehouseTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WarehouseGrpcTransport +from .transports.grpc_asyncio import WarehouseGrpcAsyncIOTransport +from .transports.rest import WarehouseRestTransport + + +class WarehouseClientMeta(type): + """Metaclass for the Warehouse 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[WarehouseTransport]] + _transport_registry["grpc"] = WarehouseGrpcTransport + _transport_registry["grpc_asyncio"] = WarehouseGrpcAsyncIOTransport + _transport_registry["rest"] = WarehouseRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WarehouseTransport]: + """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 WarehouseClient(metaclass=WarehouseClientMeta): + """Service that manages media content + metadata for streaming.""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + WarehouseClient: 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: + WarehouseClient: 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) -> WarehouseTransport: + """Returns the transport used by the client instance. + + Returns: + WarehouseTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def annotation_path(project_number: str,location: str,corpus: str,asset: str,annotation: str,) -> str: + """Returns a fully-qualified annotation string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, annotation=annotation, ) + + @staticmethod + def parse_annotation_path(path: str) -> Dict[str,str]: + """Parses a annotation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/assets/(?P.+?)/annotations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def asset_path(project_number: str,location: str,corpus: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def collection_path(project_number: str,location: str,corpus: str,collection: str,) -> str: + """Returns a fully-qualified collection string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}".format(project_number=project_number, location=location, corpus=corpus, collection=collection, ) + + @staticmethod + def parse_collection_path(path: str) -> Dict[str,str]: + """Parses a collection path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/collections/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def corpus_path(project_number: str,location: str,corpus: str,) -> str: + """Returns a fully-qualified corpus string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}".format(project_number=project_number, location=location, corpus=corpus, ) + + @staticmethod + def parse_corpus_path(path: str) -> Dict[str,str]: + """Parses a corpus path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_schema_path(project_number: str,location: str,corpus: str,data_schema: str,) -> str: + """Returns a fully-qualified data_schema string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}".format(project_number=project_number, location=location, corpus=corpus, data_schema=data_schema, ) + + @staticmethod + def parse_data_schema_path(path: str) -> Dict[str,str]: + """Parses a data_schema path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/dataSchemas/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def index_path(project_number: str,location: str,corpus: str,index: str,) -> str: + """Returns a fully-qualified index string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}".format(project_number=project_number, location=location, corpus=corpus, index=index, ) + + @staticmethod + def parse_index_path(path: str) -> Dict[str,str]: + """Parses a index path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/indexes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def index_endpoint_path(project: str,location: str,index_endpoint: str,) -> str: + """Returns a fully-qualified index_endpoint string.""" + return "projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}".format(project=project, location=location, index_endpoint=index_endpoint, ) + + @staticmethod + def parse_index_endpoint_path(path: str) -> Dict[str,str]: + """Parses a index_endpoint path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/indexEndpoints/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def search_config_path(project_number: str,location: str,corpus: str,search_config: str,) -> str: + """Returns a fully-qualified search_config string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}".format(project_number=project_number, location=location, corpus=corpus, search_config=search_config, ) + + @staticmethod + def parse_search_config_path(path: str) -> Dict[str,str]: + """Parses a search_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/searchConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def search_hypernym_path(project_number: str,location: str,corpus: str,search_hypernym: str,) -> str: + """Returns a fully-qualified search_hypernym string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}".format(project_number=project_number, location=location, corpus=corpus, search_hypernym=search_hypernym, ) + + @staticmethod + def parse_search_hypernym_path(path: str) -> Dict[str,str]: + """Parses a search_hypernym path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/searchHypernyms/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = WarehouseClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WarehouseClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = WarehouseClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WarehouseClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WarehouseClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WarehouseTransport, Callable[..., WarehouseTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the warehouse 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 (Optional[Union[str,WarehouseTransport,Callable[..., WarehouseTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the WarehouseTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = WarehouseClient._read_environment_variables() + self._client_cert_source = WarehouseClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WarehouseClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, WarehouseTransport) + if transport_provided: + # transport is a WarehouseTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(WarehouseTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WarehouseClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[WarehouseTransport], Callable[..., WarehouseTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WarehouseTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def create_asset(self, + request: Optional[Union[warehouse.CreateAssetRequest, dict]] = None, + *, + parent: Optional[str] = None, + asset: Optional[warehouse.Asset] = None, + asset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Creates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateAssetRequest, dict]): + The request object. Request message for + CreateAssetRequest. + parent (str): + Required. The parent resource where this asset will be + created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset (google.cloud.visionai_v1.types.Asset): + Required. The asset to create. + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_id (str): + Optional. The ID to use for the asset, which will become + the final component of the asset's resource name if user + choose to specify. Otherwise, asset id will be generated + by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``asset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, asset, asset_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAssetRequest): + request = warehouse.CreateAssetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if asset is not None: + request.asset = asset + if asset_id is not None: + request.asset_id = asset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_asset(self, + request: Optional[Union[warehouse.UpdateAssetRequest, dict]] = None, + *, + asset: Optional[warehouse.Asset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Updates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAssetRequest( + ) + + # Make the request + response = client.update_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateAssetRequest, dict]): + The request object. Request message for UpdateAsset. + asset (google.cloud.visionai_v1.types.Asset): + Required. The asset to update. + + The asset's ``name`` field is used to identify the asset + to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([asset, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAssetRequest): + request = warehouse.UpdateAssetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if asset is not None: + request.asset = asset + 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_asset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("asset.name", request.asset.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_asset(self, + request: Optional[Union[warehouse.GetAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Reads an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = client.get_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetAssetRequest, dict]): + The request object. Request message for GetAsset. + name (str): + Required. The name of the asset to retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAssetRequest): + request = warehouse.GetAssetRequest(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_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[warehouse.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an list of assets inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListAssetsRequest, dict]): + The request object. Request message for ListAssets. + parent (str): + Required. The parent, which owns this collection of + assets. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListAssetsPager: + Response message for ListAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAssetsRequest): + request = warehouse.ListAssetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_asset(self, + request: Optional[Union[warehouse.DeleteAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteAssetRequest, dict]): + The request object. Request message for DeleteAsset. + name (str): + Required. The name of the asset to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAssetRequest): + request = warehouse.DeleteAssetRequest(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_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteAssetMetadata, + ) + + # Done; return the response. + return response + + def upload_asset(self, + request: Optional[Union[warehouse.UploadAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Upload asset by specifing the asset Cloud Storage + uri. For video warehouse, it requires users who call + this API have read access to the cloud storage file. + Once it is uploaded, it can be retrieved by + GenerateRetrievalUrl API which by default, only can + retrieve cloud storage files from the same project of + the warehouse. To allow retrieval cloud storage files + that are in a separate project, it requires to find the + vision ai service account (Go to IAM, check checkbox to + show "Include Google-provided role grants", search for + "Cloud Vision AI Service Agent") and grant the read + access of the cloud storage files to that service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_upload_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UploadAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.upload_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UploadAssetRequest, dict]): + The request object. Request message for UploadAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UploadAssetResponse` + Response message for UploadAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UploadAssetRequest): + request = warehouse.UploadAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.upload_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.UploadAssetResponse, + metadata_type=warehouse.UploadAssetMetadata, + ) + + # Done; return the response. + return response + + def generate_retrieval_url(self, + request: Optional[Union[warehouse.GenerateRetrievalUrlRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.GenerateRetrievalUrlResponse: + r"""Generates a signed url for downloading the asset. + For video warehouse, please see comment of UploadAsset + about how to allow retrieval of cloud storage files in a + different project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_generate_retrieval_url(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateRetrievalUrlRequest( + name="name_value", + ) + + # Make the request + response = client.generate_retrieval_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GenerateRetrievalUrlRequest, dict]): + The request object. Request message for + GenerateRetrievalUrl API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.GenerateRetrievalUrlResponse: + Response message for + GenerateRetrievalUrl API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GenerateRetrievalUrlRequest): + request = warehouse.GenerateRetrievalUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_retrieval_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_asset(self, + request: Optional[Union[warehouse.AnalyzeAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Analyze asset to power search capability. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_analyze_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.AnalyzeAssetRequest, dict]): + The request object. Request message for AnalyzeAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.AnalyzeAssetResponse` + Response message for AnalyzeAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.AnalyzeAssetRequest): + request = warehouse.AnalyzeAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.AnalyzeAssetResponse, + metadata_type=warehouse.AnalyzeAssetMetadata, + ) + + # Done; return the response. + return response + + def index_asset(self, + request: Optional[Union[warehouse.IndexAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Index one asset for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_index_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.IndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.index_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.IndexAssetRequest, dict]): + The request object. Request message for IndexAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.IndexAssetResponse` + Response message for IndexAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.IndexAssetRequest): + request = warehouse.IndexAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.index_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.IndexAssetResponse, + metadata_type=warehouse.IndexAssetMetadata, + ) + + # Done; return the response. + return response + + def remove_index_asset(self, + request: Optional[Union[warehouse.RemoveIndexAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove one asset's index data for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_remove_index_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveIndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_index_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.RemoveIndexAssetRequest, dict]): + The request object. Request message for RemoveIndexAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.RemoveIndexAssetResponse` + Response message for RemoveIndexAsset. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.RemoveIndexAssetRequest): + request = warehouse.RemoveIndexAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_index_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.RemoveIndexAssetResponse, + metadata_type=warehouse.RemoveIndexAssetMetadata, + ) + + # Done; return the response. + return response + + def view_indexed_assets(self, + request: Optional[Union[warehouse.ViewIndexedAssetsRequest, dict]] = None, + *, + index: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ViewIndexedAssetsPager: + r"""Lists assets inside an index. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_view_indexed_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ViewIndexedAssetsRequest( + index="index_value", + ) + + # Make the request + page_result = client.view_indexed_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ViewIndexedAssetsRequest, dict]): + The request object. Request message for + ViewIndexedAssets. + index (str): + Required. The index that owns this collection of assets. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + + This corresponds to the ``index`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ViewIndexedAssetsPager: + Response message for + ViewIndexedAssets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([index]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ViewIndexedAssetsRequest): + request = warehouse.ViewIndexedAssetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if index is not None: + request.index = index + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.view_indexed_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index", request.index), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ViewIndexedAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_index(self, + request: Optional[Union[warehouse.CreateIndexRequest, dict]] = None, + *, + parent: Optional[str] = None, + index: Optional[warehouse.Index] = None, + index_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates an Index under the corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.CreateIndexRequest( + parent="parent_value", + index=index, + ) + + # Make the request + operation = client.create_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateIndexRequest, dict]): + The request object. Message for creating an Index. + parent (str): + Required. Value for the parent. The resource name of the + Corpus under which this index is created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index (google.cloud.visionai_v1.types.Index): + Required. The index being created. + This corresponds to the ``index`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index_id (str): + Optional. The ID for the index. This will become the + final resource name for the index. If the user does not + specify this value, it will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``index_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Index` An Index is a resource in Corpus. It contains an indexed version of the + assets and annotations. When deployed to an endpoint, + it will allow users to search the Index. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, index, index_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateIndexRequest): + request = warehouse.CreateIndexRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if index is not None: + request.index = index + if index_id is not None: + request.index_id = index_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_index] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.Index, + metadata_type=warehouse.CreateIndexMetadata, + ) + + # Done; return the response. + return response + + def update_index(self, + request: Optional[Union[warehouse.UpdateIndexRequest, dict]] = None, + *, + index: Optional[warehouse.Index] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates an Index under the corpus. Users can perform a + metadata-only update or trigger a full index rebuild with + different update_mask values. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.UpdateIndexRequest( + index=index, + ) + + # Make the request + operation = client.update_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateIndexRequest, dict]): + The request object. Request message for UpdateIndex. + index (google.cloud.visionai_v1.types.Index): + Required. The resource being updated. + This corresponds to the ``index`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Index resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field of the resource + will be overwritten if it is in the mask. Empty field + mask is not allowed. If the mask is "*", it triggers a + full update of the index, and also a whole rebuild of + index data. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Index` An Index is a resource in Corpus. It contains an indexed version of the + assets and annotations. When deployed to an endpoint, + it will allow users to search the Index. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([index, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateIndexRequest): + request = warehouse.UpdateIndexRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if index is not None: + request.index = index + 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_index] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index.name", request.index.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.Index, + metadata_type=warehouse.UpdateIndexMetadata, + ) + + # Done; return the response. + return response + + def get_index(self, + request: Optional[Union[warehouse.GetIndexRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Index: + r"""Gets the details of a single Index under a Corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexRequest( + name="name_value", + ) + + # Make the request + response = client.get_index(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetIndexRequest, dict]): + The request object. Request message for getting an Index. + name (str): + Required. Name of the Index resource. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Index: + An Index is a resource in Corpus. It + contains an indexed version of the + assets and annotations. When deployed to + an endpoint, it will allow users to + search the Index. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetIndexRequest): + request = warehouse.GetIndexRequest(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_index] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_indexes(self, + request: Optional[Union[warehouse.ListIndexesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIndexesPager: + r"""List all Indexes in a given Corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_indexes(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_indexes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListIndexesRequest, dict]): + The request object. Request message for listing Indexes. + parent (str): + Required. The parent corpus that owns this collection of + indexes. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListIndexesPager: + Response message for ListIndexes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListIndexesRequest): + request = warehouse.ListIndexesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_indexes] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListIndexesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_index(self, + request: Optional[Union[warehouse.DeleteIndexRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single Index. In order to delete an index, + the caller must make sure that it is not deployed to any + index endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteIndexRequest, dict]): + The request object. Request message for DeleteIndex. + name (str): + Required. The name of the index to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteIndexRequest): + request = warehouse.DeleteIndexRequest(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_index] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteIndexMetadata, + ) + + # Done; return the response. + return response + + def create_corpus(self, + request: Optional[Union[warehouse.CreateCorpusRequest, dict]] = None, + *, + parent: Optional[str] = None, + corpus: Optional[warehouse.Corpus] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a corpus inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateCorpusRequest, dict]): + The request object. Request message of CreateCorpus API. + parent (str): + Required. Form: + ``projects/{project_number}/locations/{location_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + corpus (google.cloud.visionai_v1.types.Corpus): + Required. The corpus to be created. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Corpus` Corpus is a set of media contents for management. + Within a corpus, media shares the same data schema. + Search is also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, corpus]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateCorpusRequest): + request = warehouse.CreateCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if corpus is not None: + request.corpus = corpus + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.Corpus, + metadata_type=warehouse.CreateCorpusMetadata, + ) + + # Done; return the response. + return response + + def get_corpus(self, + request: Optional[Union[warehouse.GetCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Gets corpus details inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = client.get_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetCorpusRequest, dict]): + The request object. Request message for GetCorpus. + name (str): + Required. The resource name of the + corpus to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Corpus: + Corpus is a set of media contents for + management. Within a corpus, media + shares the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetCorpusRequest): + request = warehouse.GetCorpusRequest(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_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_corpus(self, + request: Optional[Union[warehouse.UpdateCorpusRequest, dict]] = None, + *, + corpus: Optional[warehouse.Corpus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Updates a corpus in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = client.update_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateCorpusRequest, dict]): + The request object. Request message for UpdateCorpus. + corpus (google.cloud.visionai_v1.types.Corpus): + Required. The corpus which replaces + the resource on the server. + + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Corpus: + Corpus is a set of media contents for + management. Within a corpus, media + shares the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateCorpusRequest): + request = warehouse.UpdateCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + 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_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus.name", request.corpus.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_corpora(self, + request: Optional[Union[warehouse.ListCorporaRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCorporaPager: + r"""Lists all corpora in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_corpora(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListCorporaRequest, dict]): + The request object. Request message for ListCorpora. + parent (str): + Required. The resource name of the + project from which to list corpora. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListCorporaPager: + Response message for ListCorpora. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListCorporaRequest): + request = warehouse.ListCorporaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_corpora] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListCorporaPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_corpus(self, + request: Optional[Union[warehouse.DeleteCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a corpus only if its empty. + Returns empty response. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + client.delete_corpus(request=request) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteCorpusRequest, dict]): + The request object. Request message for DeleteCorpus. + name (str): + Required. The resource name of the + corpus to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteCorpusRequest): + request = warehouse.DeleteCorpusRequest(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_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def analyze_corpus(self, + request: Optional[Union[warehouse.AnalyzeCorpusRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Analyzes a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_analyze_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeCorpusRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_corpus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.AnalyzeCorpusRequest, dict]): + The request object. Request message for AnalyzeCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.AnalyzeCorpusResponse` + The response message for AnalyzeCorpus LRO. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.AnalyzeCorpusRequest): + request = warehouse.AnalyzeCorpusRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.AnalyzeCorpusResponse, + metadata_type=warehouse.AnalyzeCorpusMetadata, + ) + + # Done; return the response. + return response + + def create_data_schema(self, + request: Optional[Union[warehouse.CreateDataSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_schema: Optional[warehouse.DataSchema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Creates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = client.create_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateDataSchemaRequest, dict]): + The request object. Request message for CreateDataSchema. + parent (str): + Required. The parent resource where this data schema + will be created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_schema (google.cloud.visionai_v1.types.DataSchema): + Required. The data schema to create. + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_schema]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateDataSchemaRequest): + request = warehouse.CreateDataSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_schema is not None: + request.data_schema = data_schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_data_schema(self, + request: Optional[Union[warehouse.UpdateDataSchemaRequest, dict]] = None, + *, + data_schema: Optional[warehouse.DataSchema] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Updates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = client.update_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateDataSchemaRequest, dict]): + The request object. Request message for UpdateDataSchema. + data_schema (google.cloud.visionai_v1.types.DataSchema): + Required. The data schema's ``name`` field is used to + identify the data schema to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`` + + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_schema, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateDataSchemaRequest): + request = warehouse.UpdateDataSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_schema is not None: + request.data_schema = data_schema + 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_data_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_schema.name", request.data_schema.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_schema(self, + request: Optional[Union[warehouse.GetDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Gets data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetDataSchemaRequest, dict]): + The request object. Request message for GetDataSchema. + name (str): + Required. The name of the data schema to retrieve. + Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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: + google.cloud.visionai_v1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetDataSchemaRequest): + request = warehouse.GetDataSchemaRequest(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_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_data_schema(self, + request: Optional[Union[warehouse.DeleteDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + client.delete_data_schema(request=request) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteDataSchemaRequest, dict]): + The request object. Request message for DeleteDataSchema. + name (str): + Required. The name of the data schema to delete. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteDataSchemaRequest): + request = warehouse.DeleteDataSchemaRequest(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_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_data_schemas(self, + request: Optional[Union[warehouse.ListDataSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataSchemasPager: + r"""Lists a list of data schemas inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_data_schemas(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListDataSchemasRequest, dict]): + The request object. Request message for ListDataSchemas. + parent (str): + Required. The parent, which owns this collection of data + schemas. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListDataSchemasPager: + Response message for ListDataSchemas. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListDataSchemasRequest): + request = warehouse.ListDataSchemasRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_data_schemas] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListDataSchemasPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_annotation(self, + request: Optional[Union[warehouse.CreateAnnotationRequest, dict]] = None, + *, + parent: Optional[str] = None, + annotation: Optional[warehouse.Annotation] = None, + annotation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Creates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateAnnotationRequest, dict]): + The request object. Request message for CreateAnnotation. + parent (str): + Required. The parent resource where this annotation will + be created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation (google.cloud.visionai_v1.types.Annotation): + Required. The annotation to create. + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation_id (str): + Optional. The ID to use for the annotation, which will + become the final component of the annotation's resource + name if user choose to specify. Otherwise, annotation id + will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``annotation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, annotation, annotation_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAnnotationRequest): + request = warehouse.CreateAnnotationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if annotation is not None: + request.annotation = annotation + if annotation_id is not None: + request.annotation_id = annotation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_annotation(self, + request: Optional[Union[warehouse.GetAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Reads annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = client.get_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetAnnotationRequest, dict]): + The request object. Request message for GetAnnotation + API. + name (str): + Required. The name of the annotation to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAnnotationRequest): + request = warehouse.GetAnnotationRequest(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_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_annotations(self, + request: Optional[Union[warehouse.ListAnnotationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotationsPager: + r"""Lists a list of annotations inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_annotations(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListAnnotationsRequest, dict]): + The request object. Request message for GetAnnotation + API. + parent (str): + The parent, which owns this collection of annotations. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListAnnotationsPager: + Request message for ListAnnotations + API. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAnnotationsRequest): + request = warehouse.ListAnnotationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_annotations] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAnnotationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_annotation(self, + request: Optional[Union[warehouse.UpdateAnnotationRequest, dict]] = None, + *, + annotation: Optional[warehouse.Annotation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Updates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnnotationRequest( + ) + + # Make the request + response = client.update_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateAnnotationRequest, dict]): + The request object. Request message for UpdateAnnotation + API. + annotation (google.cloud.visionai_v1.types.Annotation): + Required. The annotation to update. The annotation's + ``name`` field is used to identify the annotation to be + updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([annotation, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAnnotationRequest): + request = warehouse.UpdateAnnotationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if annotation is not None: + request.annotation = annotation + 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_annotation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("annotation.name", request.annotation.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_annotation(self, + request: Optional[Union[warehouse.DeleteAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + client.delete_annotation(request=request) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteAnnotationRequest, dict]): + The request object. Request message for DeleteAnnotation + API. + name (str): + Required. The name of the annotation to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + + 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAnnotationRequest): + request = warehouse.DeleteAnnotationRequest(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_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def ingest_asset(self, + requests: Optional[Iterator[warehouse.IngestAssetRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[warehouse.IngestAssetResponse]: + r"""Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_ingest_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + config = visionai_v1.Config() + config.asset = "asset_value" + + request = visionai_v1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.ingest_asset(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1.types.IngestAssetRequest]): + The request object iterator. Request message for IngestAsset API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1.types.IngestAssetResponse]: + Response message for IngestAsset API. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.ingest_asset] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def clip_asset(self, + request: Optional[Union[warehouse.ClipAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.ClipAssetResponse: + r"""Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_clip_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = client.clip_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ClipAssetRequest, dict]): + The request object. Request message for ClipAsset API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.ClipAssetResponse: + Response message for ClipAsset API. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ClipAssetRequest): + request = warehouse.ClipAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.clip_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_hls_uri(self, + request: Optional[Union[warehouse.GenerateHlsUriRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.GenerateHlsUriResponse: + r"""Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_generate_hls_uri(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = client.generate_hls_uri(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GenerateHlsUriRequest, dict]): + The request object. Request message for GenerateHlsUri + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.GenerateHlsUriResponse: + Response message for GenerateHlsUri + API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GenerateHlsUriRequest): + request = warehouse.GenerateHlsUriRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_hls_uri] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_assets(self, + request: Optional[Union[warehouse.ImportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports assets (images plus annotations) from a meta + file on cloud storage. Each row in the meta file is + corresponding to an image (specified by a cloud storage + uri) and its annotations. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_import_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ImportAssetsRequest( + assets_gcs_uri="assets_gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_assets(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ImportAssetsRequest, dict]): + The request object. The request message for ImportAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.ImportAssetsResponse` + The response message for ImportAssets LRO. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ImportAssetsRequest): + request = warehouse.ImportAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_assets] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.ImportAssetsResponse, + metadata_type=warehouse.ImportAssetsMetadata, + ) + + # Done; return the response. + return response + + def create_search_config(self, + request: Optional[Union[warehouse.CreateSearchConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_config: Optional[warehouse.SearchConfig] = None, + search_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = client.create_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateSearchConfigRequest, dict]): + The request object. Request message for + CreateSearchConfig. + parent (str): + Required. The parent resource where this search + configuration will be created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config (google.cloud.visionai_v1.types.SearchConfig): + Required. The search config to + create. + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config_id (str): + Required. ID to use for the new search config. Will + become the final component of the SearchConfig's + resource name. This value should be up to 63 characters, + and valid characters are /[a-z][0-9]-_/. The first + character must be a letter, the last could be a letter + or a number. + + This corresponds to the ``search_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_config, search_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateSearchConfigRequest): + request = warehouse.CreateSearchConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_config is not None: + request.search_config = search_config + if search_config_id is not None: + request.search_config_id = search_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_search_config(self, + request: Optional[Union[warehouse.UpdateSearchConfigRequest, dict]] = None, + *, + search_config: Optional[warehouse.SearchConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchConfigRequest( + ) + + # Make the request + response = client.update_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateSearchConfigRequest, dict]): + The request object. Request message for + UpdateSearchConfig. + search_config (google.cloud.visionai_v1.types.SearchConfig): + Required. The search configuration to update. + + The search configuration's ``name`` field is used to + identify the resource to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If + left unset, all field paths will be + updated/overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_config, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateSearchConfigRequest): + request = warehouse.UpdateSearchConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_config is not None: + request.search_config = search_config + 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_search_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_config.name", request.search_config.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_search_config(self, + request: Optional[Union[warehouse.GetSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Gets a search configuration inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetSearchConfigRequest, dict]): + The request object. Request message for GetSearchConfig. + name (str): + Required. The name of the search configuration to + retrieve. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetSearchConfigRequest): + request = warehouse.GetSearchConfigRequest(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_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_search_config(self, + request: Optional[Union[warehouse.DeleteSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_search_config(request=request) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteSearchConfigRequest, dict]): + The request object. Request message for + DeleteSearchConfig. + name (str): + Required. The name of the search configuration to + delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + + 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteSearchConfigRequest): + request = warehouse.DeleteSearchConfigRequest(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_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_search_configs(self, + request: Optional[Union[warehouse.ListSearchConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSearchConfigsPager: + r"""Lists all search configurations inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_search_configs(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListSearchConfigsRequest, dict]): + The request object. Request message for + ListSearchConfigs. + parent (str): + Required. The parent, which owns this collection of + search configurations. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListSearchConfigsPager: + Response message for + ListSearchConfigs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListSearchConfigsRequest): + request = warehouse.ListSearchConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_search_configs] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListSearchConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_search_hypernym(self, + request: Optional[Union[warehouse.CreateSearchHypernymRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_hypernym: Optional[warehouse.SearchHypernym] = None, + search_hypernym_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchHypernym: + r"""Creates a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchHypernymRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_search_hypernym(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateSearchHypernymRequest, dict]): + The request object. Request message for creating + SearchHypernym. + parent (str): + Required. The parent resource where this SearchHypernym + will be created. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_hypernym (google.cloud.visionai_v1.types.SearchHypernym): + Required. The SearchHypernym to + create. + + This corresponds to the ``search_hypernym`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_hypernym_id (str): + Optional. The search hypernym id. + If omitted, a random UUID will be + generated. + + This corresponds to the ``search_hypernym_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchHypernym: + Search resource: SearchHypernym. + For example, { hypernym: "vehicle" hyponyms: + ["sedan", "truck"] } This means in SMART_SEARCH mode, + searching for "vehicle" will also return results with + "sedan" or "truck" as annotations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_hypernym, search_hypernym_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateSearchHypernymRequest): + request = warehouse.CreateSearchHypernymRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_hypernym is not None: + request.search_hypernym = search_hypernym + if search_hypernym_id is not None: + request.search_hypernym_id = search_hypernym_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_search_hypernym] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_search_hypernym(self, + request: Optional[Union[warehouse.UpdateSearchHypernymRequest, dict]] = None, + *, + search_hypernym: Optional[warehouse.SearchHypernym] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchHypernym: + r"""Updates a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchHypernymRequest( + ) + + # Make the request + response = client.update_search_hypernym(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateSearchHypernymRequest, dict]): + The request object. Request message for updating + SearchHypernym. + search_hypernym (google.cloud.visionai_v1.types.SearchHypernym): + Required. The SearchHypernym to update. The search + hypernym's ``name`` field is used to identify the search + hypernym to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + + This corresponds to the ``search_hypernym`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If + left unset, all field paths will be + updated/overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchHypernym: + Search resource: SearchHypernym. + For example, { hypernym: "vehicle" hyponyms: + ["sedan", "truck"] } This means in SMART_SEARCH mode, + searching for "vehicle" will also return results with + "sedan" or "truck" as annotations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_hypernym, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateSearchHypernymRequest): + request = warehouse.UpdateSearchHypernymRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_hypernym is not None: + request.search_hypernym = search_hypernym + 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_search_hypernym] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_hypernym.name", request.search_hypernym.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_search_hypernym(self, + request: Optional[Union[warehouse.GetSearchHypernymRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchHypernym: + r"""Gets a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchHypernymRequest( + name="name_value", + ) + + # Make the request + response = client.get_search_hypernym(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetSearchHypernymRequest, dict]): + The request object. Request message for getting + SearchHypernym. + name (str): + Required. The name of the SearchHypernym to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.SearchHypernym: + Search resource: SearchHypernym. + For example, { hypernym: "vehicle" hyponyms: + ["sedan", "truck"] } This means in SMART_SEARCH mode, + searching for "vehicle" will also return results with + "sedan" or "truck" as annotations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetSearchHypernymRequest): + request = warehouse.GetSearchHypernymRequest(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_search_hypernym] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_search_hypernym(self, + request: Optional[Union[warehouse.DeleteSearchHypernymRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a SearchHypernym inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchHypernymRequest( + name="name_value", + ) + + # Make the request + client.delete_search_hypernym(request=request) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteSearchHypernymRequest, dict]): + The request object. Request message for deleting + SearchHypernym. + name (str): + Required. The name of the SearchHypernym to delete. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + + 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteSearchHypernymRequest): + request = warehouse.DeleteSearchHypernymRequest(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_search_hypernym] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_search_hypernyms(self, + request: Optional[Union[warehouse.ListSearchHypernymsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSearchHypernymsPager: + r"""Lists SearchHypernyms inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_search_hypernyms(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchHypernymsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_hypernyms(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListSearchHypernymsRequest, dict]): + The request object. Request message for listing + SearchHypernyms. + parent (str): + Required. The parent, which owns this collection of + SearchHypernyms. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListSearchHypernymsPager: + Response message for listing + SearchHypernyms. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListSearchHypernymsRequest): + request = warehouse.ListSearchHypernymsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_search_hypernyms] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListSearchHypernymsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_assets(self, + request: Optional[Union[warehouse.SearchAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAssetsPager: + r"""Search media asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_search_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.SearchAssetsRequest, dict]): + The request object. Request message for SearchAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.SearchAssetsPager: + Response message for SearchAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.SearchAssetsRequest): + request = warehouse.SearchAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus", request.corpus), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.SearchAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_index_endpoint(self, + request: Optional[Union[warehouse.SearchIndexEndpointRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchIndexEndpointPager: + r"""Search a deployed index endpoint (IMAGE corpus type + only). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_search_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + image_query = visionai_v1.ImageQuery() + image_query.input_image = b'input_image_blob' + + request = visionai_v1.SearchIndexEndpointRequest( + image_query=image_query, + index_endpoint="index_endpoint_value", + ) + + # Make the request + page_result = client.search_index_endpoint(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.SearchIndexEndpointRequest, dict]): + The request object. Request message for + SearchIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.SearchIndexEndpointPager: + Response message for + SearchIndexEndpoint. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.SearchIndexEndpointRequest): + request = warehouse.SearchIndexEndpointRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint", request.index_endpoint), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.SearchIndexEndpointPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_index_endpoint(self, + request: Optional[Union[warehouse.CreateIndexEndpointRequest, dict]] = None, + *, + parent: Optional[str] = None, + index_endpoint: Optional[warehouse.IndexEndpoint] = None, + index_endpoint_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateIndexEndpointRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateIndexEndpointRequest, dict]): + The request object. Request message for + CreateIndexEndpoint. + parent (str): + Required. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index_endpoint (google.cloud.visionai_v1.types.IndexEndpoint): + Required. The resource being created. + This corresponds to the ``index_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + index_endpoint_id (str): + Optional. The ID to use for the + IndexEndpoint, which will become the + final component of the IndexEndpoint's + resource name if the user specifies it. + Otherwise, IndexEndpoint id will be + autogenerated. + + This value should be up to 63 + characters, and valid characters are + a-z, 0-9 and dash (-). The first + character must be a letter, the last + must be a letter or a number. + + This corresponds to the ``index_endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.IndexEndpoint` + Message representing IndexEndpoint resource. Indexes are + deployed into it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, index_endpoint, index_endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateIndexEndpointRequest): + request = warehouse.CreateIndexEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if index_endpoint is not None: + request.index_endpoint = index_endpoint + if index_endpoint_id is not None: + request.index_endpoint_id = index_endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.IndexEndpoint, + metadata_type=warehouse.CreateIndexEndpointMetadata, + ) + + # Done; return the response. + return response + + def get_index_endpoint(self, + request: Optional[Union[warehouse.GetIndexEndpointRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.IndexEndpoint: + r"""Gets an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexEndpointRequest( + name="name_value", + ) + + # Make the request + response = client.get_index_endpoint(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetIndexEndpointRequest, dict]): + The request object. Request message for GetIndexEndpoint. + name (str): + Required. Name of the IndexEndpoint + resource. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.IndexEndpoint: + Message representing IndexEndpoint + resource. Indexes are deployed into it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetIndexEndpointRequest): + request = warehouse.GetIndexEndpointRequest(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_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_index_endpoints(self, + request: Optional[Union[warehouse.ListIndexEndpointsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIndexEndpointsPager: + r"""Lists all IndexEndpoints in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_index_endpoints(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_index_endpoints(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListIndexEndpointsRequest, dict]): + The request object. Request message for + ListIndexEndpoints. + parent (str): + Required. Format: + ``projects/{project}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListIndexEndpointsPager: + Response message for + ListIndexEndpoints. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListIndexEndpointsRequest): + request = warehouse.ListIndexEndpointsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_index_endpoints] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListIndexEndpointsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_index_endpoint(self, + request: Optional[Union[warehouse.UpdateIndexEndpointRequest, dict]] = None, + *, + index_endpoint: Optional[warehouse.IndexEndpoint] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateIndexEndpointRequest( + ) + + # Make the request + operation = client.update_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateIndexEndpointRequest, dict]): + The request object. Request message for + UpdateIndexEndpoint. + index_endpoint (google.cloud.visionai_v1.types.IndexEndpoint): + Required. The resource being updated. + This corresponds to the ``index_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the IndexEndpoint resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field of the + resource will be overwritten if it is in the mask. Empty + field mask is not allowed. If the mask is "*", then this + is a full replacement of the resource. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.IndexEndpoint` + Message representing IndexEndpoint resource. Indexes are + deployed into it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([index_endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateIndexEndpointRequest): + request = warehouse.UpdateIndexEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if index_endpoint is not None: + request.index_endpoint = index_endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint.name", request.index_endpoint.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.IndexEndpoint, + metadata_type=warehouse.UpdateIndexEndpointMetadata, + ) + + # Done; return the response. + return response + + def delete_index_endpoint(self, + request: Optional[Union[warehouse.DeleteIndexEndpointRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes an IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexEndpointRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteIndexEndpointRequest, dict]): + The request object. Request message for + DeleteIndexEndpoint. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteIndexEndpointRequest): + request = warehouse.DeleteIndexEndpointRequest(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_index_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteIndexEndpointMetadata, + ) + + # Done; return the response. + return response + + def deploy_index(self, + request: Optional[Union[warehouse.DeployIndexRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deploys an Index to IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_deploy_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + deployed_index = visionai_v1.DeployedIndex() + deployed_index.index = "index_value" + + request = visionai_v1.DeployIndexRequest( + index_endpoint="index_endpoint_value", + deployed_index=deployed_index, + ) + + # Make the request + operation = client.deploy_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeployIndexRequest, dict]): + The request object. Request message for DeployIndex. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.DeployIndexResponse` + DeployIndex response once the operation is done. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeployIndexRequest): + request = warehouse.DeployIndexRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.deploy_index] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint", request.index_endpoint), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.DeployIndexResponse, + metadata_type=warehouse.DeployIndexMetadata, + ) + + # Done; return the response. + return response + + def undeploy_index(self, + request: Optional[Union[warehouse.UndeployIndexRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Undeploys an Index from IndexEndpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_undeploy_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployIndexRequest( + index_endpoint="index_endpoint_value", + ) + + # Make the request + operation = client.undeploy_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UndeployIndexRequest, dict]): + The request object. Request message for + UndeployIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1.types.UndeployIndexResponse` + UndeployIndex response once the operation is done. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UndeployIndexRequest): + request = warehouse.UndeployIndexRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undeploy_index] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("index_endpoint", request.index_endpoint), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.UndeployIndexResponse, + metadata_type=warehouse.UndeployIndexMetadata, + ) + + # Done; return the response. + return response + + def create_collection(self, + request: Optional[Union[warehouse.CreateCollectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + collection: Optional[warehouse.Collection] = None, + collection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_create_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateCollectionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_collection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.CreateCollectionRequest, dict]): + The request object. Request message for CreateCollection. + parent (str): + Required. The parent resource where this collection will + be created. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + collection (google.cloud.visionai_v1.types.Collection): + Required. The collection resource to + be created. + + This corresponds to the ``collection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + collection_id (str): + Optional. The ID to use for the collection, which will + become the final component of the resource name if user + choose to specify. Otherwise, collection id will be + generated by system. + + This value should be up to 55 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``collection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1.types.Collection` A collection is a resource in a corpus. It serves as a container of + references to original resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, collection, collection_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateCollectionRequest): + request = warehouse.CreateCollectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if collection is not None: + request.collection = collection + if collection_id is not None: + request.collection_id = collection_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_collection] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.Collection, + metadata_type=warehouse.CreateCollectionMetadata, + ) + + # Done; return the response. + return response + + def delete_collection(self, + request: Optional[Union[warehouse.DeleteCollectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_delete_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCollectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_collection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.DeleteCollectionRequest, dict]): + The request object. Request message for + DeleteCollectionRequest. + name (str): + Required. The name of the collection to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteCollectionRequest): + request = warehouse.DeleteCollectionRequest(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_collection] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteCollectionMetadata, + ) + + # Done; return the response. + return response + + def get_collection(self, + request: Optional[Union[warehouse.GetCollectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Collection: + r"""Gets a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_get_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetCollectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.GetCollectionRequest, dict]): + The request object. Request message for + GetCollectionRequest. + name (str): + Required. The name of the collection to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Collection: + A collection is a resource in a + corpus. It serves as a container of + references to original resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetCollectionRequest): + request = warehouse.GetCollectionRequest(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_collection] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_collection(self, + request: Optional[Union[warehouse.UpdateCollectionRequest, dict]] = None, + *, + collection: Optional[warehouse.Collection] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Collection: + r"""Updates a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_update_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateCollectionRequest( + ) + + # Make the request + response = client.update_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.UpdateCollectionRequest, dict]): + The request object. Request message for + UpdateCollectionRequest. + collection (google.cloud.visionai_v1.types.Collection): + Required. The collection to update. + + The collection's ``name`` field is used to identify the + collection to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``collection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + + - Unset ``update_mask`` or set ``update_mask`` to be a + single "*" only will update all updatable fields with + the value provided in ``collection``. + - To update ``display_name`` value to empty string, set + it in the ``collection`` to empty string, and set + ``update_mask`` with "display_name". Same applies to + other updatable string fields in the ``collection``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.Collection: + A collection is a resource in a + corpus. It serves as a container of + references to original resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([collection, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateCollectionRequest): + request = warehouse.UpdateCollectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if collection is not None: + request.collection = collection + 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_collection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("collection.name", request.collection.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_collections(self, + request: Optional[Union[warehouse.ListCollectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCollectionsPager: + r"""Lists collections inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_list_collections(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_collections(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ListCollectionsRequest, dict]): + The request object. Request message for ListCollections. + parent (str): + Required. The parent corpus. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ListCollectionsPager: + Response message for ListCollections. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListCollectionsRequest): + request = warehouse.ListCollectionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_collections] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListCollectionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_collection_item(self, + request: Optional[Union[warehouse.AddCollectionItemRequest, dict]] = None, + *, + item: Optional[warehouse.CollectionItem] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.AddCollectionItemResponse: + r"""Adds an item into a Collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_add_collection_item(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.AddCollectionItemRequest( + item=item, + ) + + # Make the request + response = client.add_collection_item(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.AddCollectionItemRequest, dict]): + The request object. Request message for + AddCollectionItem. + item (google.cloud.visionai_v1.types.CollectionItem): + Required. The item to be added. + This corresponds to the ``item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.AddCollectionItemResponse: + Response message for + AddCollectionItem. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([item]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.AddCollectionItemRequest): + request = warehouse.AddCollectionItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if item is not None: + request.item = item + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_collection_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("item.collection", request.item.collection), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_collection_item(self, + request: Optional[Union[warehouse.RemoveCollectionItemRequest, dict]] = None, + *, + item: Optional[warehouse.CollectionItem] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.RemoveCollectionItemResponse: + r"""Removes an item from a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_remove_collection_item(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.RemoveCollectionItemRequest( + item=item, + ) + + # Make the request + response = client.remove_collection_item(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.RemoveCollectionItemRequest, dict]): + The request object. Request message for + RemoveCollectionItem. + item (google.cloud.visionai_v1.types.CollectionItem): + Required. The item to be removed. + This corresponds to the ``item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.types.RemoveCollectionItemResponse: + Request message for + RemoveCollectionItem. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([item]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.RemoveCollectionItemRequest): + request = warehouse.RemoveCollectionItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if item is not None: + request.item = item + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_collection_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("item.collection", request.item.collection), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def view_collection_items(self, + request: Optional[Union[warehouse.ViewCollectionItemsRequest, dict]] = None, + *, + collection: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ViewCollectionItemsPager: + r"""View items inside a collection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1 + + def sample_view_collection_items(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ViewCollectionItemsRequest( + collection="collection_value", + ) + + # Make the request + page_result = client.view_collection_items(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1.types.ViewCollectionItemsRequest, dict]): + The request object. Request message for + ViewCollectionItems. + collection (str): + Required. The collection to view. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + + This corresponds to the ``collection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1.services.warehouse.pagers.ViewCollectionItemsPager: + Response message for + ViewCollectionItems. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([collection]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ViewCollectionItemsRequest): + request = warehouse.ViewCollectionItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if collection is not None: + request.collection = collection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.view_collection_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("collection", request.collection), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ViewCollectionItemsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "WarehouseClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "WarehouseClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/pagers.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/pagers.py new file mode 100644 index 000000000000..29575da4317a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/pagers.py @@ -0,0 +1,1591 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1.types import warehouse + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListAssetsResponse` + 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[..., warehouse.ListAssetsResponse], + request: warehouse.ListAssetsRequest, + response: warehouse.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListAssetsResponse): + 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 = warehouse.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Asset]: + for page in self.pages: + yield from page.assets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListAssetsResponse` + 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[warehouse.ListAssetsResponse]], + request: warehouse.ListAssetsRequest, + response: warehouse.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListAssetsResponse): + 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 = warehouse.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Asset]: + async def async_generator(): + async for page in self.pages: + for response in page.assets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ViewIndexedAssetsPager: + """A pager for iterating through ``view_indexed_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ViewIndexedAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``indexed_assets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ViewIndexedAssets`` requests and continue to iterate + through the ``indexed_assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ViewIndexedAssetsResponse` + 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[..., warehouse.ViewIndexedAssetsResponse], + request: warehouse.ViewIndexedAssetsRequest, + response: warehouse.ViewIndexedAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ViewIndexedAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ViewIndexedAssetsResponse): + 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 = warehouse.ViewIndexedAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ViewIndexedAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.IndexedAsset]: + for page in self.pages: + yield from page.indexed_assets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ViewIndexedAssetsAsyncPager: + """A pager for iterating through ``view_indexed_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ViewIndexedAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``indexed_assets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ViewIndexedAssets`` requests and continue to iterate + through the ``indexed_assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ViewIndexedAssetsResponse` + 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[warehouse.ViewIndexedAssetsResponse]], + request: warehouse.ViewIndexedAssetsRequest, + response: warehouse.ViewIndexedAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ViewIndexedAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ViewIndexedAssetsResponse): + 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 = warehouse.ViewIndexedAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ViewIndexedAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.IndexedAsset]: + async def async_generator(): + async for page in self.pages: + for response in page.indexed_assets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIndexesPager: + """A pager for iterating through ``list_indexes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListIndexesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``indexes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIndexes`` requests and continue to iterate + through the ``indexes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListIndexesResponse` + 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[..., warehouse.ListIndexesResponse], + request: warehouse.ListIndexesRequest, + response: warehouse.ListIndexesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListIndexesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListIndexesResponse): + 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 = warehouse.ListIndexesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListIndexesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Index]: + for page in self.pages: + yield from page.indexes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIndexesAsyncPager: + """A pager for iterating through ``list_indexes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListIndexesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``indexes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIndexes`` requests and continue to iterate + through the ``indexes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListIndexesResponse` + 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[warehouse.ListIndexesResponse]], + request: warehouse.ListIndexesRequest, + response: warehouse.ListIndexesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListIndexesRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListIndexesResponse): + 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 = warehouse.ListIndexesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListIndexesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Index]: + async def async_generator(): + async for page in self.pages: + for response in page.indexes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCorporaPager: + """A pager for iterating through ``list_corpora`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListCorporaResponse` object, and + provides an ``__iter__`` method to iterate through its + ``corpora`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCorpora`` requests and continue to iterate + through the ``corpora`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListCorporaResponse` + 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[..., warehouse.ListCorporaResponse], + request: warehouse.ListCorporaRequest, + response: warehouse.ListCorporaResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListCorporaRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListCorporaResponse): + 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 = warehouse.ListCorporaRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListCorporaResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Corpus]: + for page in self.pages: + yield from page.corpora + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCorporaAsyncPager: + """A pager for iterating through ``list_corpora`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListCorporaResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``corpora`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCorpora`` requests and continue to iterate + through the ``corpora`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListCorporaResponse` + 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[warehouse.ListCorporaResponse]], + request: warehouse.ListCorporaRequest, + response: warehouse.ListCorporaResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListCorporaRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListCorporaResponse): + 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 = warehouse.ListCorporaRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListCorporaResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Corpus]: + async def async_generator(): + async for page in self.pages: + for response in page.corpora: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataSchemasPager: + """A pager for iterating through ``list_data_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListDataSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataSchemas`` requests and continue to iterate + through the ``data_schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListDataSchemasResponse` + 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[..., warehouse.ListDataSchemasResponse], + request: warehouse.ListDataSchemasRequest, + response: warehouse.ListDataSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListDataSchemasRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListDataSchemasResponse): + 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 = warehouse.ListDataSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListDataSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.DataSchema]: + for page in self.pages: + yield from page.data_schemas + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataSchemasAsyncPager: + """A pager for iterating through ``list_data_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListDataSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataSchemas`` requests and continue to iterate + through the ``data_schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListDataSchemasResponse` + 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[warehouse.ListDataSchemasResponse]], + request: warehouse.ListDataSchemasRequest, + response: warehouse.ListDataSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListDataSchemasRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListDataSchemasResponse): + 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 = warehouse.ListDataSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListDataSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.DataSchema]: + async def async_generator(): + async for page in self.pages: + for response in page.data_schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotationsPager: + """A pager for iterating through ``list_annotations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListAnnotationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``annotations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnnotations`` requests and continue to iterate + through the ``annotations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListAnnotationsResponse` + 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[..., warehouse.ListAnnotationsResponse], + request: warehouse.ListAnnotationsRequest, + response: warehouse.ListAnnotationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListAnnotationsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListAnnotationsResponse): + 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 = warehouse.ListAnnotationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListAnnotationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Annotation]: + for page in self.pages: + yield from page.annotations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotationsAsyncPager: + """A pager for iterating through ``list_annotations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListAnnotationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``annotations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnnotations`` requests and continue to iterate + through the ``annotations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListAnnotationsResponse` + 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[warehouse.ListAnnotationsResponse]], + request: warehouse.ListAnnotationsRequest, + response: warehouse.ListAnnotationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListAnnotationsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListAnnotationsResponse): + 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 = warehouse.ListAnnotationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListAnnotationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Annotation]: + async def async_generator(): + async for page in self.pages: + for response in page.annotations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchConfigsPager: + """A pager for iterating through ``list_search_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListSearchConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``search_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSearchConfigs`` requests and continue to iterate + through the ``search_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListSearchConfigsResponse` + 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[..., warehouse.ListSearchConfigsResponse], + request: warehouse.ListSearchConfigsRequest, + response: warehouse.ListSearchConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListSearchConfigsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListSearchConfigsResponse): + 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 = warehouse.ListSearchConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListSearchConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.SearchConfig]: + for page in self.pages: + yield from page.search_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchConfigsAsyncPager: + """A pager for iterating through ``list_search_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListSearchConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``search_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSearchConfigs`` requests and continue to iterate + through the ``search_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListSearchConfigsResponse` + 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[warehouse.ListSearchConfigsResponse]], + request: warehouse.ListSearchConfigsRequest, + response: warehouse.ListSearchConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListSearchConfigsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListSearchConfigsResponse): + 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 = warehouse.ListSearchConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListSearchConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.SearchConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.search_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchHypernymsPager: + """A pager for iterating through ``list_search_hypernyms`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListSearchHypernymsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``search_hypernyms`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSearchHypernyms`` requests and continue to iterate + through the ``search_hypernyms`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListSearchHypernymsResponse` + 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[..., warehouse.ListSearchHypernymsResponse], + request: warehouse.ListSearchHypernymsRequest, + response: warehouse.ListSearchHypernymsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListSearchHypernymsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListSearchHypernymsResponse): + 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 = warehouse.ListSearchHypernymsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListSearchHypernymsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.SearchHypernym]: + for page in self.pages: + yield from page.search_hypernyms + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchHypernymsAsyncPager: + """A pager for iterating through ``list_search_hypernyms`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListSearchHypernymsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``search_hypernyms`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSearchHypernyms`` requests and continue to iterate + through the ``search_hypernyms`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListSearchHypernymsResponse` + 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[warehouse.ListSearchHypernymsResponse]], + request: warehouse.ListSearchHypernymsRequest, + response: warehouse.ListSearchHypernymsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListSearchHypernymsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListSearchHypernymsResponse): + 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 = warehouse.ListSearchHypernymsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListSearchHypernymsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.SearchHypernym]: + async def async_generator(): + async for page in self.pages: + for response in page.search_hypernyms: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAssetsPager: + """A pager for iterating through ``search_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.SearchAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``search_result_items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAssets`` requests and continue to iterate + through the ``search_result_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.SearchAssetsResponse` + 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[..., warehouse.SearchAssetsResponse], + request: warehouse.SearchAssetsRequest, + response: warehouse.SearchAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.SearchAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.SearchAssetsResponse): + 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 = warehouse.SearchAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.SearchAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.SearchResultItem]: + for page in self.pages: + yield from page.search_result_items + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAssetsAsyncPager: + """A pager for iterating through ``search_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.SearchAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``search_result_items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAssets`` requests and continue to iterate + through the ``search_result_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.SearchAssetsResponse` + 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[warehouse.SearchAssetsResponse]], + request: warehouse.SearchAssetsRequest, + response: warehouse.SearchAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.SearchAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.SearchAssetsResponse): + 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 = warehouse.SearchAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.SearchAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.SearchResultItem]: + async def async_generator(): + async for page in self.pages: + for response in page.search_result_items: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchIndexEndpointPager: + """A pager for iterating through ``search_index_endpoint`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.SearchIndexEndpointResponse` object, and + provides an ``__iter__`` method to iterate through its + ``search_result_items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchIndexEndpoint`` requests and continue to iterate + through the ``search_result_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.SearchIndexEndpointResponse` + 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[..., warehouse.SearchIndexEndpointResponse], + request: warehouse.SearchIndexEndpointRequest, + response: warehouse.SearchIndexEndpointResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.SearchIndexEndpointRequest): + The initial request object. + response (google.cloud.visionai_v1.types.SearchIndexEndpointResponse): + 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 = warehouse.SearchIndexEndpointRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.SearchIndexEndpointResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.SearchResultItem]: + for page in self.pages: + yield from page.search_result_items + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchIndexEndpointAsyncPager: + """A pager for iterating through ``search_index_endpoint`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.SearchIndexEndpointResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``search_result_items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchIndexEndpoint`` requests and continue to iterate + through the ``search_result_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.SearchIndexEndpointResponse` + 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[warehouse.SearchIndexEndpointResponse]], + request: warehouse.SearchIndexEndpointRequest, + response: warehouse.SearchIndexEndpointResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.SearchIndexEndpointRequest): + The initial request object. + response (google.cloud.visionai_v1.types.SearchIndexEndpointResponse): + 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 = warehouse.SearchIndexEndpointRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.SearchIndexEndpointResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.SearchResultItem]: + async def async_generator(): + async for page in self.pages: + for response in page.search_result_items: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIndexEndpointsPager: + """A pager for iterating through ``list_index_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListIndexEndpointsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``index_endpoints`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIndexEndpoints`` requests and continue to iterate + through the ``index_endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListIndexEndpointsResponse` + 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[..., warehouse.ListIndexEndpointsResponse], + request: warehouse.ListIndexEndpointsRequest, + response: warehouse.ListIndexEndpointsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListIndexEndpointsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListIndexEndpointsResponse): + 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 = warehouse.ListIndexEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListIndexEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.IndexEndpoint]: + for page in self.pages: + yield from page.index_endpoints + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIndexEndpointsAsyncPager: + """A pager for iterating through ``list_index_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListIndexEndpointsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``index_endpoints`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIndexEndpoints`` requests and continue to iterate + through the ``index_endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListIndexEndpointsResponse` + 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[warehouse.ListIndexEndpointsResponse]], + request: warehouse.ListIndexEndpointsRequest, + response: warehouse.ListIndexEndpointsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListIndexEndpointsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListIndexEndpointsResponse): + 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 = warehouse.ListIndexEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListIndexEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.IndexEndpoint]: + async def async_generator(): + async for page in self.pages: + for response in page.index_endpoints: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCollectionsPager: + """A pager for iterating through ``list_collections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListCollectionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``collections`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCollections`` requests and continue to iterate + through the ``collections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListCollectionsResponse` + 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[..., warehouse.ListCollectionsResponse], + request: warehouse.ListCollectionsRequest, + response: warehouse.ListCollectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListCollectionsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListCollectionsResponse): + 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 = warehouse.ListCollectionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListCollectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Collection]: + for page in self.pages: + yield from page.collections + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCollectionsAsyncPager: + """A pager for iterating through ``list_collections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ListCollectionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``collections`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCollections`` requests and continue to iterate + through the ``collections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ListCollectionsResponse` + 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[warehouse.ListCollectionsResponse]], + request: warehouse.ListCollectionsRequest, + response: warehouse.ListCollectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ListCollectionsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ListCollectionsResponse): + 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 = warehouse.ListCollectionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListCollectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Collection]: + async def async_generator(): + async for page in self.pages: + for response in page.collections: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ViewCollectionItemsPager: + """A pager for iterating through ``view_collection_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ViewCollectionItemsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ViewCollectionItems`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ViewCollectionItemsResponse` + 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[..., warehouse.ViewCollectionItemsResponse], + request: warehouse.ViewCollectionItemsRequest, + response: warehouse.ViewCollectionItemsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ViewCollectionItemsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ViewCollectionItemsResponse): + 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 = warehouse.ViewCollectionItemsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ViewCollectionItemsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.CollectionItem]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ViewCollectionItemsAsyncPager: + """A pager for iterating through ``view_collection_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1.types.ViewCollectionItemsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ViewCollectionItems`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1.types.ViewCollectionItemsResponse` + 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[warehouse.ViewCollectionItemsResponse]], + request: warehouse.ViewCollectionItemsRequest, + response: warehouse.ViewCollectionItemsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1.types.ViewCollectionItemsRequest): + The initial request object. + response (google.cloud.visionai_v1.types.ViewCollectionItemsResponse): + 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 = warehouse.ViewCollectionItemsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ViewCollectionItemsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.CollectionItem]: + async def async_generator(): + async for page in self.pages: + for response in page.items: + 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/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/__init__.py new file mode 100644 index 000000000000..c7ec5d9728c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 WarehouseTransport +from .grpc import WarehouseGrpcTransport +from .grpc_asyncio import WarehouseGrpcAsyncIOTransport +from .rest import WarehouseRestTransport +from .rest import WarehouseRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WarehouseTransport]] +_transport_registry['grpc'] = WarehouseGrpcTransport +_transport_registry['grpc_asyncio'] = WarehouseGrpcAsyncIOTransport +_transport_registry['rest'] = WarehouseRestTransport + +__all__ = ( + 'WarehouseTransport', + 'WarehouseGrpcTransport', + 'WarehouseGrpcAsyncIOTransport', + 'WarehouseRestTransport', + 'WarehouseRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/base.py new file mode 100644 index 000000000000..875797ed8574 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/base.py @@ -0,0 +1,1112 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WarehouseTransport(abc.ABC): + """Abstract transport class for Warehouse.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_asset: gapic_v1.method.wrap_method( + self.create_asset, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_asset: gapic_v1.method.wrap_method( + self.update_asset, + default_timeout=None, + client_info=client_info, + ), + self.get_asset: gapic_v1.method.wrap_method( + self.get_asset, + default_timeout=None, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_timeout=None, + client_info=client_info, + ), + self.delete_asset: gapic_v1.method.wrap_method( + self.delete_asset, + default_timeout=None, + client_info=client_info, + ), + self.upload_asset: gapic_v1.method.wrap_method( + self.upload_asset, + default_timeout=None, + client_info=client_info, + ), + self.generate_retrieval_url: gapic_v1.method.wrap_method( + self.generate_retrieval_url, + default_timeout=None, + client_info=client_info, + ), + self.analyze_asset: gapic_v1.method.wrap_method( + self.analyze_asset, + default_timeout=None, + client_info=client_info, + ), + self.index_asset: gapic_v1.method.wrap_method( + self.index_asset, + default_timeout=None, + client_info=client_info, + ), + self.remove_index_asset: gapic_v1.method.wrap_method( + self.remove_index_asset, + default_timeout=None, + client_info=client_info, + ), + self.view_indexed_assets: gapic_v1.method.wrap_method( + self.view_indexed_assets, + default_timeout=None, + client_info=client_info, + ), + self.create_index: gapic_v1.method.wrap_method( + self.create_index, + default_timeout=None, + client_info=client_info, + ), + self.update_index: gapic_v1.method.wrap_method( + self.update_index, + default_timeout=None, + client_info=client_info, + ), + self.get_index: gapic_v1.method.wrap_method( + self.get_index, + default_timeout=None, + client_info=client_info, + ), + self.list_indexes: gapic_v1.method.wrap_method( + self.list_indexes, + default_timeout=None, + client_info=client_info, + ), + self.delete_index: gapic_v1.method.wrap_method( + self.delete_index, + default_timeout=None, + client_info=client_info, + ), + self.create_corpus: gapic_v1.method.wrap_method( + self.create_corpus, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_corpus: gapic_v1.method.wrap_method( + self.get_corpus, + default_timeout=None, + client_info=client_info, + ), + self.update_corpus: gapic_v1.method.wrap_method( + self.update_corpus, + default_timeout=None, + client_info=client_info, + ), + self.list_corpora: gapic_v1.method.wrap_method( + self.list_corpora, + default_timeout=None, + client_info=client_info, + ), + self.delete_corpus: gapic_v1.method.wrap_method( + self.delete_corpus, + default_timeout=None, + client_info=client_info, + ), + self.analyze_corpus: gapic_v1.method.wrap_method( + self.analyze_corpus, + default_timeout=None, + client_info=client_info, + ), + self.create_data_schema: gapic_v1.method.wrap_method( + self.create_data_schema, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_data_schema: gapic_v1.method.wrap_method( + self.update_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.get_data_schema: gapic_v1.method.wrap_method( + self.get_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_schema: gapic_v1.method.wrap_method( + self.delete_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_data_schemas: gapic_v1.method.wrap_method( + self.list_data_schemas, + default_timeout=None, + client_info=client_info, + ), + self.create_annotation: gapic_v1.method.wrap_method( + self.create_annotation, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_annotation: gapic_v1.method.wrap_method( + self.get_annotation, + default_timeout=None, + client_info=client_info, + ), + self.list_annotations: gapic_v1.method.wrap_method( + self.list_annotations, + default_timeout=None, + client_info=client_info, + ), + self.update_annotation: gapic_v1.method.wrap_method( + self.update_annotation, + default_timeout=None, + client_info=client_info, + ), + self.delete_annotation: gapic_v1.method.wrap_method( + self.delete_annotation, + default_timeout=None, + client_info=client_info, + ), + self.ingest_asset: gapic_v1.method.wrap_method( + self.ingest_asset, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.clip_asset: gapic_v1.method.wrap_method( + self.clip_asset, + default_timeout=None, + client_info=client_info, + ), + self.generate_hls_uri: gapic_v1.method.wrap_method( + self.generate_hls_uri, + default_timeout=None, + client_info=client_info, + ), + self.import_assets: gapic_v1.method.wrap_method( + self.import_assets, + default_timeout=None, + client_info=client_info, + ), + self.create_search_config: gapic_v1.method.wrap_method( + self.create_search_config, + default_timeout=None, + client_info=client_info, + ), + self.update_search_config: gapic_v1.method.wrap_method( + self.update_search_config, + default_timeout=None, + client_info=client_info, + ), + self.get_search_config: gapic_v1.method.wrap_method( + self.get_search_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_config: gapic_v1.method.wrap_method( + self.delete_search_config, + default_timeout=None, + client_info=client_info, + ), + self.list_search_configs: gapic_v1.method.wrap_method( + self.list_search_configs, + default_timeout=None, + client_info=client_info, + ), + self.create_search_hypernym: gapic_v1.method.wrap_method( + self.create_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.update_search_hypernym: gapic_v1.method.wrap_method( + self.update_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.get_search_hypernym: gapic_v1.method.wrap_method( + self.get_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_hypernym: gapic_v1.method.wrap_method( + self.delete_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.list_search_hypernyms: gapic_v1.method.wrap_method( + self.list_search_hypernyms, + default_timeout=None, + client_info=client_info, + ), + self.search_assets: gapic_v1.method.wrap_method( + self.search_assets, + default_timeout=None, + client_info=client_info, + ), + self.search_index_endpoint: gapic_v1.method.wrap_method( + self.search_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.create_index_endpoint: gapic_v1.method.wrap_method( + self.create_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.get_index_endpoint: gapic_v1.method.wrap_method( + self.get_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.list_index_endpoints: gapic_v1.method.wrap_method( + self.list_index_endpoints, + default_timeout=None, + client_info=client_info, + ), + self.update_index_endpoint: gapic_v1.method.wrap_method( + self.update_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.delete_index_endpoint: gapic_v1.method.wrap_method( + self.delete_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.deploy_index: gapic_v1.method.wrap_method( + self.deploy_index, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_index: gapic_v1.method.wrap_method( + self.undeploy_index, + default_timeout=None, + client_info=client_info, + ), + self.create_collection: gapic_v1.method.wrap_method( + self.create_collection, + default_timeout=None, + client_info=client_info, + ), + self.delete_collection: gapic_v1.method.wrap_method( + self.delete_collection, + default_timeout=None, + client_info=client_info, + ), + self.get_collection: gapic_v1.method.wrap_method( + self.get_collection, + default_timeout=None, + client_info=client_info, + ), + self.update_collection: gapic_v1.method.wrap_method( + self.update_collection, + default_timeout=None, + client_info=client_info, + ), + self.list_collections: gapic_v1.method.wrap_method( + self.list_collections, + default_timeout=None, + client_info=client_info, + ), + self.add_collection_item: gapic_v1.method.wrap_method( + self.add_collection_item, + default_timeout=None, + client_info=client_info, + ), + self.remove_collection_item: gapic_v1.method.wrap_method( + self.remove_collection_item, + default_timeout=None, + client_info=client_info, + ), + self.view_collection_items: gapic_v1.method.wrap_method( + self.view_collection_items, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + Union[ + warehouse.Asset, + Awaitable[warehouse.Asset] + ]]: + raise NotImplementedError() + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + Union[ + warehouse.Asset, + Awaitable[warehouse.Asset] + ]]: + raise NotImplementedError() + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + Union[ + warehouse.Asset, + Awaitable[warehouse.Asset] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + Union[ + warehouse.ListAssetsResponse, + Awaitable[warehouse.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def upload_asset(self) -> Callable[ + [warehouse.UploadAssetRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_retrieval_url(self) -> Callable[ + [warehouse.GenerateRetrievalUrlRequest], + Union[ + warehouse.GenerateRetrievalUrlResponse, + Awaitable[warehouse.GenerateRetrievalUrlResponse] + ]]: + raise NotImplementedError() + + @property + def analyze_asset(self) -> Callable[ + [warehouse.AnalyzeAssetRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def index_asset(self) -> Callable[ + [warehouse.IndexAssetRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_index_asset(self) -> Callable[ + [warehouse.RemoveIndexAssetRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def view_indexed_assets(self) -> Callable[ + [warehouse.ViewIndexedAssetsRequest], + Union[ + warehouse.ViewIndexedAssetsResponse, + Awaitable[warehouse.ViewIndexedAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def create_index(self) -> Callable[ + [warehouse.CreateIndexRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_index(self) -> Callable[ + [warehouse.UpdateIndexRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_index(self) -> Callable[ + [warehouse.GetIndexRequest], + Union[ + warehouse.Index, + Awaitable[warehouse.Index] + ]]: + raise NotImplementedError() + + @property + def list_indexes(self) -> Callable[ + [warehouse.ListIndexesRequest], + Union[ + warehouse.ListIndexesResponse, + Awaitable[warehouse.ListIndexesResponse] + ]]: + raise NotImplementedError() + + @property + def delete_index(self) -> Callable[ + [warehouse.DeleteIndexRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + Union[ + warehouse.Corpus, + Awaitable[warehouse.Corpus] + ]]: + raise NotImplementedError() + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + Union[ + warehouse.Corpus, + Awaitable[warehouse.Corpus] + ]]: + raise NotImplementedError() + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + Union[ + warehouse.ListCorporaResponse, + Awaitable[warehouse.ListCorporaResponse] + ]]: + raise NotImplementedError() + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def analyze_corpus(self) -> Callable[ + [warehouse.AnalyzeCorpusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + Union[ + warehouse.DataSchema, + Awaitable[warehouse.DataSchema] + ]]: + raise NotImplementedError() + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + Union[ + warehouse.DataSchema, + Awaitable[warehouse.DataSchema] + ]]: + raise NotImplementedError() + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + Union[ + warehouse.DataSchema, + Awaitable[warehouse.DataSchema] + ]]: + raise NotImplementedError() + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + Union[ + warehouse.ListDataSchemasResponse, + Awaitable[warehouse.ListDataSchemasResponse] + ]]: + raise NotImplementedError() + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + Union[ + warehouse.Annotation, + Awaitable[warehouse.Annotation] + ]]: + raise NotImplementedError() + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + Union[ + warehouse.Annotation, + Awaitable[warehouse.Annotation] + ]]: + raise NotImplementedError() + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + Union[ + warehouse.ListAnnotationsResponse, + Awaitable[warehouse.ListAnnotationsResponse] + ]]: + raise NotImplementedError() + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + Union[ + warehouse.Annotation, + Awaitable[warehouse.Annotation] + ]]: + raise NotImplementedError() + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + Union[ + warehouse.IngestAssetResponse, + Awaitable[warehouse.IngestAssetResponse] + ]]: + raise NotImplementedError() + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + Union[ + warehouse.ClipAssetResponse, + Awaitable[warehouse.ClipAssetResponse] + ]]: + raise NotImplementedError() + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + Union[ + warehouse.GenerateHlsUriResponse, + Awaitable[warehouse.GenerateHlsUriResponse] + ]]: + raise NotImplementedError() + + @property + def import_assets(self) -> Callable[ + [warehouse.ImportAssetsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + Union[ + warehouse.SearchConfig, + Awaitable[warehouse.SearchConfig] + ]]: + raise NotImplementedError() + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + Union[ + warehouse.SearchConfig, + Awaitable[warehouse.SearchConfig] + ]]: + raise NotImplementedError() + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + Union[ + warehouse.SearchConfig, + Awaitable[warehouse.SearchConfig] + ]]: + raise NotImplementedError() + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + Union[ + warehouse.ListSearchConfigsResponse, + Awaitable[warehouse.ListSearchConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def create_search_hypernym(self) -> Callable[ + [warehouse.CreateSearchHypernymRequest], + Union[ + warehouse.SearchHypernym, + Awaitable[warehouse.SearchHypernym] + ]]: + raise NotImplementedError() + + @property + def update_search_hypernym(self) -> Callable[ + [warehouse.UpdateSearchHypernymRequest], + Union[ + warehouse.SearchHypernym, + Awaitable[warehouse.SearchHypernym] + ]]: + raise NotImplementedError() + + @property + def get_search_hypernym(self) -> Callable[ + [warehouse.GetSearchHypernymRequest], + Union[ + warehouse.SearchHypernym, + Awaitable[warehouse.SearchHypernym] + ]]: + raise NotImplementedError() + + @property + def delete_search_hypernym(self) -> Callable[ + [warehouse.DeleteSearchHypernymRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_search_hypernyms(self) -> Callable[ + [warehouse.ListSearchHypernymsRequest], + Union[ + warehouse.ListSearchHypernymsResponse, + Awaitable[warehouse.ListSearchHypernymsResponse] + ]]: + raise NotImplementedError() + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + Union[ + warehouse.SearchAssetsResponse, + Awaitable[warehouse.SearchAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def search_index_endpoint(self) -> Callable[ + [warehouse.SearchIndexEndpointRequest], + Union[ + warehouse.SearchIndexEndpointResponse, + Awaitable[warehouse.SearchIndexEndpointResponse] + ]]: + raise NotImplementedError() + + @property + def create_index_endpoint(self) -> Callable[ + [warehouse.CreateIndexEndpointRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_index_endpoint(self) -> Callable[ + [warehouse.GetIndexEndpointRequest], + Union[ + warehouse.IndexEndpoint, + Awaitable[warehouse.IndexEndpoint] + ]]: + raise NotImplementedError() + + @property + def list_index_endpoints(self) -> Callable[ + [warehouse.ListIndexEndpointsRequest], + Union[ + warehouse.ListIndexEndpointsResponse, + Awaitable[warehouse.ListIndexEndpointsResponse] + ]]: + raise NotImplementedError() + + @property + def update_index_endpoint(self) -> Callable[ + [warehouse.UpdateIndexEndpointRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_index_endpoint(self) -> Callable[ + [warehouse.DeleteIndexEndpointRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def deploy_index(self) -> Callable[ + [warehouse.DeployIndexRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def undeploy_index(self) -> Callable[ + [warehouse.UndeployIndexRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_collection(self) -> Callable[ + [warehouse.CreateCollectionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_collection(self) -> Callable[ + [warehouse.DeleteCollectionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_collection(self) -> Callable[ + [warehouse.GetCollectionRequest], + Union[ + warehouse.Collection, + Awaitable[warehouse.Collection] + ]]: + raise NotImplementedError() + + @property + def update_collection(self) -> Callable[ + [warehouse.UpdateCollectionRequest], + Union[ + warehouse.Collection, + Awaitable[warehouse.Collection] + ]]: + raise NotImplementedError() + + @property + def list_collections(self) -> Callable[ + [warehouse.ListCollectionsRequest], + Union[ + warehouse.ListCollectionsResponse, + Awaitable[warehouse.ListCollectionsResponse] + ]]: + raise NotImplementedError() + + @property + def add_collection_item(self) -> Callable[ + [warehouse.AddCollectionItemRequest], + Union[ + warehouse.AddCollectionItemResponse, + Awaitable[warehouse.AddCollectionItemResponse] + ]]: + raise NotImplementedError() + + @property + def remove_collection_item(self) -> Callable[ + [warehouse.RemoveCollectionItemRequest], + Union[ + warehouse.RemoveCollectionItemResponse, + Awaitable[warehouse.RemoveCollectionItemResponse] + ]]: + raise NotImplementedError() + + @property + def view_collection_items(self) -> Callable[ + [warehouse.ViewCollectionItemsRequest], + Union[ + warehouse.ViewCollectionItemsResponse, + Awaitable[warehouse.ViewCollectionItemsResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WarehouseTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/grpc.py new file mode 100644 index 000000000000..f1d91c806e47 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/grpc.py @@ -0,0 +1,2044 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import WarehouseTransport, DEFAULT_CLIENT_INFO + + +class WarehouseGrpcTransport(WarehouseTransport): + """gRPC backend transport for Warehouse. + + Service that manages media content + metadata for streaming. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + warehouse.Asset]: + r"""Return a callable for the create asset method over gRPC. + + Creates an asset inside corpus. + + Returns: + Callable[[~.CreateAssetRequest], + ~.Asset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['create_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateAsset', + request_serializer=warehouse.CreateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['create_asset'] + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + warehouse.Asset]: + r"""Return a callable for the update asset method over gRPC. + + Updates an asset inside corpus. + + Returns: + Callable[[~.UpdateAssetRequest], + ~.Asset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['update_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateAsset', + request_serializer=warehouse.UpdateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['update_asset'] + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + warehouse.Asset]: + r"""Return a callable for the get asset method over gRPC. + + Reads an asset inside corpus. + + Returns: + Callable[[~.GetAssetRequest], + ~.Asset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['get_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetAsset', + request_serializer=warehouse.GetAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['get_asset'] + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + warehouse.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an list of assets inside corpus. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListAssets', + request_serializer=warehouse.ListAssetsRequest.serialize, + response_deserializer=warehouse.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete asset method over gRPC. + + Deletes asset inside corpus. + + Returns: + Callable[[~.DeleteAssetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_asset' not in self._stubs: + self._stubs['delete_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteAsset', + request_serializer=warehouse.DeleteAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_asset'] + + @property + def upload_asset(self) -> Callable[ + [warehouse.UploadAssetRequest], + operations_pb2.Operation]: + r"""Return a callable for the upload asset method over gRPC. + + Upload asset by specifing the asset Cloud Storage + uri. For video warehouse, it requires users who call + this API have read access to the cloud storage file. + Once it is uploaded, it can be retrieved by + GenerateRetrievalUrl API which by default, only can + retrieve cloud storage files from the same project of + the warehouse. To allow retrieval cloud storage files + that are in a separate project, it requires to find the + vision ai service account (Go to IAM, check checkbox to + show "Include Google-provided role grants", search for + "Cloud Vision AI Service Agent") and grant the read + access of the cloud storage files to that service + account. + + Returns: + Callable[[~.UploadAssetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'upload_asset' not in self._stubs: + self._stubs['upload_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UploadAsset', + request_serializer=warehouse.UploadAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['upload_asset'] + + @property + def generate_retrieval_url(self) -> Callable[ + [warehouse.GenerateRetrievalUrlRequest], + warehouse.GenerateRetrievalUrlResponse]: + r"""Return a callable for the generate retrieval url method over gRPC. + + Generates a signed url for downloading the asset. + For video warehouse, please see comment of UploadAsset + about how to allow retrieval of cloud storage files in a + different project. + + Returns: + Callable[[~.GenerateRetrievalUrlRequest], + ~.GenerateRetrievalUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_retrieval_url' not in self._stubs: + self._stubs['generate_retrieval_url'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GenerateRetrievalUrl', + request_serializer=warehouse.GenerateRetrievalUrlRequest.serialize, + response_deserializer=warehouse.GenerateRetrievalUrlResponse.deserialize, + ) + return self._stubs['generate_retrieval_url'] + + @property + def analyze_asset(self) -> Callable[ + [warehouse.AnalyzeAssetRequest], + operations_pb2.Operation]: + r"""Return a callable for the analyze asset method over gRPC. + + Analyze asset to power search capability. + + Returns: + Callable[[~.AnalyzeAssetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_asset' not in self._stubs: + self._stubs['analyze_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/AnalyzeAsset', + request_serializer=warehouse.AnalyzeAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['analyze_asset'] + + @property + def index_asset(self) -> Callable[ + [warehouse.IndexAssetRequest], + operations_pb2.Operation]: + r"""Return a callable for the index asset method over gRPC. + + Index one asset for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + Returns: + Callable[[~.IndexAssetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'index_asset' not in self._stubs: + self._stubs['index_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/IndexAsset', + request_serializer=warehouse.IndexAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['index_asset'] + + @property + def remove_index_asset(self) -> Callable[ + [warehouse.RemoveIndexAssetRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove index asset method over gRPC. + + Remove one asset's index data for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + Returns: + Callable[[~.RemoveIndexAssetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_index_asset' not in self._stubs: + self._stubs['remove_index_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/RemoveIndexAsset', + request_serializer=warehouse.RemoveIndexAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_index_asset'] + + @property + def view_indexed_assets(self) -> Callable[ + [warehouse.ViewIndexedAssetsRequest], + warehouse.ViewIndexedAssetsResponse]: + r"""Return a callable for the view indexed assets method over gRPC. + + Lists assets inside an index. + + Returns: + Callable[[~.ViewIndexedAssetsRequest], + ~.ViewIndexedAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'view_indexed_assets' not in self._stubs: + self._stubs['view_indexed_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ViewIndexedAssets', + request_serializer=warehouse.ViewIndexedAssetsRequest.serialize, + response_deserializer=warehouse.ViewIndexedAssetsResponse.deserialize, + ) + return self._stubs['view_indexed_assets'] + + @property + def create_index(self) -> Callable[ + [warehouse.CreateIndexRequest], + operations_pb2.Operation]: + r"""Return a callable for the create index method over gRPC. + + Creates an Index under the corpus. + + Returns: + Callable[[~.CreateIndexRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_index' not in self._stubs: + self._stubs['create_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateIndex', + request_serializer=warehouse.CreateIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_index'] + + @property + def update_index(self) -> Callable[ + [warehouse.UpdateIndexRequest], + operations_pb2.Operation]: + r"""Return a callable for the update index method over gRPC. + + Updates an Index under the corpus. Users can perform a + metadata-only update or trigger a full index rebuild with + different update_mask values. + + Returns: + Callable[[~.UpdateIndexRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_index' not in self._stubs: + self._stubs['update_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateIndex', + request_serializer=warehouse.UpdateIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_index'] + + @property + def get_index(self) -> Callable[ + [warehouse.GetIndexRequest], + warehouse.Index]: + r"""Return a callable for the get index method over gRPC. + + Gets the details of a single Index under a Corpus. + + Returns: + Callable[[~.GetIndexRequest], + ~.Index]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_index' not in self._stubs: + self._stubs['get_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetIndex', + request_serializer=warehouse.GetIndexRequest.serialize, + response_deserializer=warehouse.Index.deserialize, + ) + return self._stubs['get_index'] + + @property + def list_indexes(self) -> Callable[ + [warehouse.ListIndexesRequest], + warehouse.ListIndexesResponse]: + r"""Return a callable for the list indexes method over gRPC. + + List all Indexes in a given Corpus. + + Returns: + Callable[[~.ListIndexesRequest], + ~.ListIndexesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_indexes' not in self._stubs: + self._stubs['list_indexes'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListIndexes', + request_serializer=warehouse.ListIndexesRequest.serialize, + response_deserializer=warehouse.ListIndexesResponse.deserialize, + ) + return self._stubs['list_indexes'] + + @property + def delete_index(self) -> Callable[ + [warehouse.DeleteIndexRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete index method over gRPC. + + Delete a single Index. In order to delete an index, + the caller must make sure that it is not deployed to any + index endpoint. + + Returns: + Callable[[~.DeleteIndexRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_index' not in self._stubs: + self._stubs['delete_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteIndex', + request_serializer=warehouse.DeleteIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_index'] + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + operations_pb2.Operation]: + r"""Return a callable for the create corpus method over gRPC. + + Creates a corpus inside a project. + + Returns: + Callable[[~.CreateCorpusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_corpus' not in self._stubs: + self._stubs['create_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateCorpus', + request_serializer=warehouse.CreateCorpusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_corpus'] + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + warehouse.Corpus]: + r"""Return a callable for the get corpus method over gRPC. + + Gets corpus details inside a project. + + Returns: + Callable[[~.GetCorpusRequest], + ~.Corpus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['get_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetCorpus', + request_serializer=warehouse.GetCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['get_corpus'] + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + warehouse.Corpus]: + r"""Return a callable for the update corpus method over gRPC. + + Updates a corpus in a project. + + Returns: + Callable[[~.UpdateCorpusRequest], + ~.Corpus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['update_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateCorpus', + request_serializer=warehouse.UpdateCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['update_corpus'] + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + warehouse.ListCorporaResponse]: + r"""Return a callable for the list corpora method over gRPC. + + Lists all corpora in a project. + + Returns: + Callable[[~.ListCorporaRequest], + ~.ListCorporaResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpora' not in self._stubs: + self._stubs['list_corpora'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListCorpora', + request_serializer=warehouse.ListCorporaRequest.serialize, + response_deserializer=warehouse.ListCorporaResponse.deserialize, + ) + return self._stubs['list_corpora'] + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete corpus method over gRPC. + + Deletes a corpus only if its empty. + Returns empty response. + + Returns: + Callable[[~.DeleteCorpusRequest], + ~.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_corpus' not in self._stubs: + self._stubs['delete_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteCorpus', + request_serializer=warehouse.DeleteCorpusRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_corpus'] + + @property + def analyze_corpus(self) -> Callable[ + [warehouse.AnalyzeCorpusRequest], + operations_pb2.Operation]: + r"""Return a callable for the analyze corpus method over gRPC. + + Analyzes a corpus. + + Returns: + Callable[[~.AnalyzeCorpusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_corpus' not in self._stubs: + self._stubs['analyze_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/AnalyzeCorpus', + request_serializer=warehouse.AnalyzeCorpusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['analyze_corpus'] + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + warehouse.DataSchema]: + r"""Return a callable for the create data schema method over gRPC. + + Creates data schema inside corpus. + + Returns: + Callable[[~.CreateDataSchemaRequest], + ~.DataSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['create_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateDataSchema', + request_serializer=warehouse.CreateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['create_data_schema'] + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + warehouse.DataSchema]: + r"""Return a callable for the update data schema method over gRPC. + + Updates data schema inside corpus. + + Returns: + Callable[[~.UpdateDataSchemaRequest], + ~.DataSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['update_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateDataSchema', + request_serializer=warehouse.UpdateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['update_data_schema'] + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + warehouse.DataSchema]: + r"""Return a callable for the get data schema method over gRPC. + + Gets data schema inside corpus. + + Returns: + Callable[[~.GetDataSchemaRequest], + ~.DataSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['get_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetDataSchema', + request_serializer=warehouse.GetDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['get_data_schema'] + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete data schema method over gRPC. + + Deletes data schema inside corpus. + + Returns: + Callable[[~.DeleteDataSchemaRequest], + ~.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_data_schema' not in self._stubs: + self._stubs['delete_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteDataSchema', + request_serializer=warehouse.DeleteDataSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_schema'] + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + warehouse.ListDataSchemasResponse]: + r"""Return a callable for the list data schemas method over gRPC. + + Lists a list of data schemas inside corpus. + + Returns: + Callable[[~.ListDataSchemasRequest], + ~.ListDataSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schemas' not in self._stubs: + self._stubs['list_data_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListDataSchemas', + request_serializer=warehouse.ListDataSchemasRequest.serialize, + response_deserializer=warehouse.ListDataSchemasResponse.deserialize, + ) + return self._stubs['list_data_schemas'] + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + warehouse.Annotation]: + r"""Return a callable for the create annotation method over gRPC. + + Creates annotation inside asset. + + Returns: + Callable[[~.CreateAnnotationRequest], + ~.Annotation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['create_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateAnnotation', + request_serializer=warehouse.CreateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['create_annotation'] + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + warehouse.Annotation]: + r"""Return a callable for the get annotation method over gRPC. + + Reads annotation inside asset. + + Returns: + Callable[[~.GetAnnotationRequest], + ~.Annotation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['get_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetAnnotation', + request_serializer=warehouse.GetAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['get_annotation'] + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + warehouse.ListAnnotationsResponse]: + r"""Return a callable for the list annotations method over gRPC. + + Lists a list of annotations inside asset. + + Returns: + Callable[[~.ListAnnotationsRequest], + ~.ListAnnotationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotations' not in self._stubs: + self._stubs['list_annotations'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListAnnotations', + request_serializer=warehouse.ListAnnotationsRequest.serialize, + response_deserializer=warehouse.ListAnnotationsResponse.deserialize, + ) + return self._stubs['list_annotations'] + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + warehouse.Annotation]: + r"""Return a callable for the update annotation method over gRPC. + + Updates annotation inside asset. + + Returns: + Callable[[~.UpdateAnnotationRequest], + ~.Annotation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['update_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateAnnotation', + request_serializer=warehouse.UpdateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['update_annotation'] + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete annotation method over gRPC. + + Deletes annotation inside asset. + + Returns: + Callable[[~.DeleteAnnotationRequest], + ~.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_annotation' not in self._stubs: + self._stubs['delete_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteAnnotation', + request_serializer=warehouse.DeleteAnnotationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotation'] + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + warehouse.IngestAssetResponse]: + r"""Return a callable for the ingest asset method over gRPC. + + Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + Returns: + Callable[[~.IngestAssetRequest], + ~.IngestAssetResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'ingest_asset' not in self._stubs: + self._stubs['ingest_asset'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.Warehouse/IngestAsset', + request_serializer=warehouse.IngestAssetRequest.serialize, + response_deserializer=warehouse.IngestAssetResponse.deserialize, + ) + return self._stubs['ingest_asset'] + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + warehouse.ClipAssetResponse]: + r"""Return a callable for the clip asset method over gRPC. + + Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + Returns: + Callable[[~.ClipAssetRequest], + ~.ClipAssetResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'clip_asset' not in self._stubs: + self._stubs['clip_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ClipAsset', + request_serializer=warehouse.ClipAssetRequest.serialize, + response_deserializer=warehouse.ClipAssetResponse.deserialize, + ) + return self._stubs['clip_asset'] + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + warehouse.GenerateHlsUriResponse]: + r"""Return a callable for the generate hls uri method over gRPC. + + Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + Returns: + Callable[[~.GenerateHlsUriRequest], + ~.GenerateHlsUriResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_hls_uri' not in self._stubs: + self._stubs['generate_hls_uri'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GenerateHlsUri', + request_serializer=warehouse.GenerateHlsUriRequest.serialize, + response_deserializer=warehouse.GenerateHlsUriResponse.deserialize, + ) + return self._stubs['generate_hls_uri'] + + @property + def import_assets(self) -> Callable[ + [warehouse.ImportAssetsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import assets method over gRPC. + + Imports assets (images plus annotations) from a meta + file on cloud storage. Each row in the meta file is + corresponding to an image (specified by a cloud storage + uri) and its annotations. + + Returns: + Callable[[~.ImportAssetsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_assets' not in self._stubs: + self._stubs['import_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ImportAssets', + request_serializer=warehouse.ImportAssetsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_assets'] + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + warehouse.SearchConfig]: + r"""Return a callable for the create search config method over gRPC. + + Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.CreateSearchConfigRequest], + ~.SearchConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['create_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateSearchConfig', + request_serializer=warehouse.CreateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['create_search_config'] + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + warehouse.SearchConfig]: + r"""Return a callable for the update search config method over gRPC. + + Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.UpdateSearchConfigRequest], + ~.SearchConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['update_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateSearchConfig', + request_serializer=warehouse.UpdateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['update_search_config'] + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + warehouse.SearchConfig]: + r"""Return a callable for the get search config method over gRPC. + + Gets a search configuration inside a corpus. + + Returns: + Callable[[~.GetSearchConfigRequest], + ~.SearchConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['get_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetSearchConfig', + request_serializer=warehouse.GetSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['get_search_config'] + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete search config method over gRPC. + + Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + Returns: + Callable[[~.DeleteSearchConfigRequest], + ~.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_search_config' not in self._stubs: + self._stubs['delete_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteSearchConfig', + request_serializer=warehouse.DeleteSearchConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_config'] + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + warehouse.ListSearchConfigsResponse]: + r"""Return a callable for the list search configs method over gRPC. + + Lists all search configurations inside a corpus. + + Returns: + Callable[[~.ListSearchConfigsRequest], + ~.ListSearchConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_configs' not in self._stubs: + self._stubs['list_search_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListSearchConfigs', + request_serializer=warehouse.ListSearchConfigsRequest.serialize, + response_deserializer=warehouse.ListSearchConfigsResponse.deserialize, + ) + return self._stubs['list_search_configs'] + + @property + def create_search_hypernym(self) -> Callable[ + [warehouse.CreateSearchHypernymRequest], + warehouse.SearchHypernym]: + r"""Return a callable for the create search hypernym method over gRPC. + + Creates a SearchHypernym inside a corpus. + + Returns: + Callable[[~.CreateSearchHypernymRequest], + ~.SearchHypernym]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernym' not in self._stubs: + self._stubs['create_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateSearchHypernym', + request_serializer=warehouse.CreateSearchHypernymRequest.serialize, + response_deserializer=warehouse.SearchHypernym.deserialize, + ) + return self._stubs['create_search_hypernym'] + + @property + def update_search_hypernym(self) -> Callable[ + [warehouse.UpdateSearchHypernymRequest], + warehouse.SearchHypernym]: + r"""Return a callable for the update search hypernym method over gRPC. + + Updates a SearchHypernym inside a corpus. + + Returns: + Callable[[~.UpdateSearchHypernymRequest], + ~.SearchHypernym]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernym' not in self._stubs: + self._stubs['update_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateSearchHypernym', + request_serializer=warehouse.UpdateSearchHypernymRequest.serialize, + response_deserializer=warehouse.SearchHypernym.deserialize, + ) + return self._stubs['update_search_hypernym'] + + @property + def get_search_hypernym(self) -> Callable[ + [warehouse.GetSearchHypernymRequest], + warehouse.SearchHypernym]: + r"""Return a callable for the get search hypernym method over gRPC. + + Gets a SearchHypernym inside a corpus. + + Returns: + Callable[[~.GetSearchHypernymRequest], + ~.SearchHypernym]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernym' not in self._stubs: + self._stubs['get_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetSearchHypernym', + request_serializer=warehouse.GetSearchHypernymRequest.serialize, + response_deserializer=warehouse.SearchHypernym.deserialize, + ) + return self._stubs['get_search_hypernym'] + + @property + def delete_search_hypernym(self) -> Callable[ + [warehouse.DeleteSearchHypernymRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete search hypernym method over gRPC. + + Deletes a SearchHypernym inside a corpus. + + Returns: + Callable[[~.DeleteSearchHypernymRequest], + ~.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_search_hypernym' not in self._stubs: + self._stubs['delete_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteSearchHypernym', + request_serializer=warehouse.DeleteSearchHypernymRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_hypernym'] + + @property + def list_search_hypernyms(self) -> Callable[ + [warehouse.ListSearchHypernymsRequest], + warehouse.ListSearchHypernymsResponse]: + r"""Return a callable for the list search hypernyms method over gRPC. + + Lists SearchHypernyms inside a corpus. + + Returns: + Callable[[~.ListSearchHypernymsRequest], + ~.ListSearchHypernymsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernyms' not in self._stubs: + self._stubs['list_search_hypernyms'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListSearchHypernyms', + request_serializer=warehouse.ListSearchHypernymsRequest.serialize, + response_deserializer=warehouse.ListSearchHypernymsResponse.deserialize, + ) + return self._stubs['list_search_hypernyms'] + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + warehouse.SearchAssetsResponse]: + r"""Return a callable for the search assets method over gRPC. + + Search media asset. + + Returns: + Callable[[~.SearchAssetsRequest], + ~.SearchAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_assets' not in self._stubs: + self._stubs['search_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/SearchAssets', + request_serializer=warehouse.SearchAssetsRequest.serialize, + response_deserializer=warehouse.SearchAssetsResponse.deserialize, + ) + return self._stubs['search_assets'] + + @property + def search_index_endpoint(self) -> Callable[ + [warehouse.SearchIndexEndpointRequest], + warehouse.SearchIndexEndpointResponse]: + r"""Return a callable for the search index endpoint method over gRPC. + + Search a deployed index endpoint (IMAGE corpus type + only). + + Returns: + Callable[[~.SearchIndexEndpointRequest], + ~.SearchIndexEndpointResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_index_endpoint' not in self._stubs: + self._stubs['search_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/SearchIndexEndpoint', + request_serializer=warehouse.SearchIndexEndpointRequest.serialize, + response_deserializer=warehouse.SearchIndexEndpointResponse.deserialize, + ) + return self._stubs['search_index_endpoint'] + + @property + def create_index_endpoint(self) -> Callable[ + [warehouse.CreateIndexEndpointRequest], + operations_pb2.Operation]: + r"""Return a callable for the create index endpoint method over gRPC. + + Creates an IndexEndpoint. + + Returns: + Callable[[~.CreateIndexEndpointRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_index_endpoint' not in self._stubs: + self._stubs['create_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateIndexEndpoint', + request_serializer=warehouse.CreateIndexEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_index_endpoint'] + + @property + def get_index_endpoint(self) -> Callable[ + [warehouse.GetIndexEndpointRequest], + warehouse.IndexEndpoint]: + r"""Return a callable for the get index endpoint method over gRPC. + + Gets an IndexEndpoint. + + Returns: + Callable[[~.GetIndexEndpointRequest], + ~.IndexEndpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_index_endpoint' not in self._stubs: + self._stubs['get_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetIndexEndpoint', + request_serializer=warehouse.GetIndexEndpointRequest.serialize, + response_deserializer=warehouse.IndexEndpoint.deserialize, + ) + return self._stubs['get_index_endpoint'] + + @property + def list_index_endpoints(self) -> Callable[ + [warehouse.ListIndexEndpointsRequest], + warehouse.ListIndexEndpointsResponse]: + r"""Return a callable for the list index endpoints method over gRPC. + + Lists all IndexEndpoints in a project. + + Returns: + Callable[[~.ListIndexEndpointsRequest], + ~.ListIndexEndpointsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_index_endpoints' not in self._stubs: + self._stubs['list_index_endpoints'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListIndexEndpoints', + request_serializer=warehouse.ListIndexEndpointsRequest.serialize, + response_deserializer=warehouse.ListIndexEndpointsResponse.deserialize, + ) + return self._stubs['list_index_endpoints'] + + @property + def update_index_endpoint(self) -> Callable[ + [warehouse.UpdateIndexEndpointRequest], + operations_pb2.Operation]: + r"""Return a callable for the update index endpoint method over gRPC. + + Updates an IndexEndpoint. + + Returns: + Callable[[~.UpdateIndexEndpointRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_index_endpoint' not in self._stubs: + self._stubs['update_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateIndexEndpoint', + request_serializer=warehouse.UpdateIndexEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_index_endpoint'] + + @property + def delete_index_endpoint(self) -> Callable[ + [warehouse.DeleteIndexEndpointRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete index endpoint method over gRPC. + + Deletes an IndexEndpoint. + + Returns: + Callable[[~.DeleteIndexEndpointRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_index_endpoint' not in self._stubs: + self._stubs['delete_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteIndexEndpoint', + request_serializer=warehouse.DeleteIndexEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_index_endpoint'] + + @property + def deploy_index(self) -> Callable[ + [warehouse.DeployIndexRequest], + operations_pb2.Operation]: + r"""Return a callable for the deploy index method over gRPC. + + Deploys an Index to IndexEndpoint. + + Returns: + Callable[[~.DeployIndexRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_index' not in self._stubs: + self._stubs['deploy_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeployIndex', + request_serializer=warehouse.DeployIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_index'] + + @property + def undeploy_index(self) -> Callable[ + [warehouse.UndeployIndexRequest], + operations_pb2.Operation]: + r"""Return a callable for the undeploy index method over gRPC. + + Undeploys an Index from IndexEndpoint. + + Returns: + Callable[[~.UndeployIndexRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undeploy_index' not in self._stubs: + self._stubs['undeploy_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UndeployIndex', + request_serializer=warehouse.UndeployIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_index'] + + @property + def create_collection(self) -> Callable[ + [warehouse.CreateCollectionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create collection method over gRPC. + + Creates a collection. + + Returns: + Callable[[~.CreateCollectionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_collection' not in self._stubs: + self._stubs['create_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateCollection', + request_serializer=warehouse.CreateCollectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_collection'] + + @property + def delete_collection(self) -> Callable[ + [warehouse.DeleteCollectionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete collection method over gRPC. + + Deletes a collection. + + Returns: + Callable[[~.DeleteCollectionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_collection' not in self._stubs: + self._stubs['delete_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteCollection', + request_serializer=warehouse.DeleteCollectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_collection'] + + @property + def get_collection(self) -> Callable[ + [warehouse.GetCollectionRequest], + warehouse.Collection]: + r"""Return a callable for the get collection method over gRPC. + + Gets a collection. + + Returns: + Callable[[~.GetCollectionRequest], + ~.Collection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_collection' not in self._stubs: + self._stubs['get_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetCollection', + request_serializer=warehouse.GetCollectionRequest.serialize, + response_deserializer=warehouse.Collection.deserialize, + ) + return self._stubs['get_collection'] + + @property + def update_collection(self) -> Callable[ + [warehouse.UpdateCollectionRequest], + warehouse.Collection]: + r"""Return a callable for the update collection method over gRPC. + + Updates a collection. + + Returns: + Callable[[~.UpdateCollectionRequest], + ~.Collection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_collection' not in self._stubs: + self._stubs['update_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateCollection', + request_serializer=warehouse.UpdateCollectionRequest.serialize, + response_deserializer=warehouse.Collection.deserialize, + ) + return self._stubs['update_collection'] + + @property + def list_collections(self) -> Callable[ + [warehouse.ListCollectionsRequest], + warehouse.ListCollectionsResponse]: + r"""Return a callable for the list collections method over gRPC. + + Lists collections inside a corpus. + + Returns: + Callable[[~.ListCollectionsRequest], + ~.ListCollectionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_collections' not in self._stubs: + self._stubs['list_collections'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListCollections', + request_serializer=warehouse.ListCollectionsRequest.serialize, + response_deserializer=warehouse.ListCollectionsResponse.deserialize, + ) + return self._stubs['list_collections'] + + @property + def add_collection_item(self) -> Callable[ + [warehouse.AddCollectionItemRequest], + warehouse.AddCollectionItemResponse]: + r"""Return a callable for the add collection item method over gRPC. + + Adds an item into a Collection. + + Returns: + Callable[[~.AddCollectionItemRequest], + ~.AddCollectionItemResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_collection_item' not in self._stubs: + self._stubs['add_collection_item'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/AddCollectionItem', + request_serializer=warehouse.AddCollectionItemRequest.serialize, + response_deserializer=warehouse.AddCollectionItemResponse.deserialize, + ) + return self._stubs['add_collection_item'] + + @property + def remove_collection_item(self) -> Callable[ + [warehouse.RemoveCollectionItemRequest], + warehouse.RemoveCollectionItemResponse]: + r"""Return a callable for the remove collection item method over gRPC. + + Removes an item from a collection. + + Returns: + Callable[[~.RemoveCollectionItemRequest], + ~.RemoveCollectionItemResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_collection_item' not in self._stubs: + self._stubs['remove_collection_item'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/RemoveCollectionItem', + request_serializer=warehouse.RemoveCollectionItemRequest.serialize, + response_deserializer=warehouse.RemoveCollectionItemResponse.deserialize, + ) + return self._stubs['remove_collection_item'] + + @property + def view_collection_items(self) -> Callable[ + [warehouse.ViewCollectionItemsRequest], + warehouse.ViewCollectionItemsResponse]: + r"""Return a callable for the view collection items method over gRPC. + + View items inside a collection. + + Returns: + Callable[[~.ViewCollectionItemsRequest], + ~.ViewCollectionItemsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'view_collection_items' not in self._stubs: + self._stubs['view_collection_items'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ViewCollectionItems', + request_serializer=warehouse.ViewCollectionItemsRequest.serialize, + response_deserializer=warehouse.ViewCollectionItemsResponse.deserialize, + ) + return self._stubs['view_collection_items'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WarehouseGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c1776a409e35 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/grpc_asyncio.py @@ -0,0 +1,2409 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import WarehouseTransport, DEFAULT_CLIENT_INFO +from .grpc import WarehouseGrpcTransport + + +class WarehouseGrpcAsyncIOTransport(WarehouseTransport): + """gRPC AsyncIO backend transport for Warehouse. + + Service that manages media content + metadata for streaming. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + Awaitable[warehouse.Asset]]: + r"""Return a callable for the create asset method over gRPC. + + Creates an asset inside corpus. + + Returns: + Callable[[~.CreateAssetRequest], + Awaitable[~.Asset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['create_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateAsset', + request_serializer=warehouse.CreateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['create_asset'] + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + Awaitable[warehouse.Asset]]: + r"""Return a callable for the update asset method over gRPC. + + Updates an asset inside corpus. + + Returns: + Callable[[~.UpdateAssetRequest], + Awaitable[~.Asset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['update_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateAsset', + request_serializer=warehouse.UpdateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['update_asset'] + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + Awaitable[warehouse.Asset]]: + r"""Return a callable for the get asset method over gRPC. + + Reads an asset inside corpus. + + Returns: + Callable[[~.GetAssetRequest], + Awaitable[~.Asset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['get_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetAsset', + request_serializer=warehouse.GetAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['get_asset'] + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + Awaitable[warehouse.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an list of assets inside corpus. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListAssets', + request_serializer=warehouse.ListAssetsRequest.serialize, + response_deserializer=warehouse.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete asset method over gRPC. + + Deletes asset inside corpus. + + Returns: + Callable[[~.DeleteAssetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_asset' not in self._stubs: + self._stubs['delete_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteAsset', + request_serializer=warehouse.DeleteAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_asset'] + + @property + def upload_asset(self) -> Callable[ + [warehouse.UploadAssetRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the upload asset method over gRPC. + + Upload asset by specifing the asset Cloud Storage + uri. For video warehouse, it requires users who call + this API have read access to the cloud storage file. + Once it is uploaded, it can be retrieved by + GenerateRetrievalUrl API which by default, only can + retrieve cloud storage files from the same project of + the warehouse. To allow retrieval cloud storage files + that are in a separate project, it requires to find the + vision ai service account (Go to IAM, check checkbox to + show "Include Google-provided role grants", search for + "Cloud Vision AI Service Agent") and grant the read + access of the cloud storage files to that service + account. + + Returns: + Callable[[~.UploadAssetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'upload_asset' not in self._stubs: + self._stubs['upload_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UploadAsset', + request_serializer=warehouse.UploadAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['upload_asset'] + + @property + def generate_retrieval_url(self) -> Callable[ + [warehouse.GenerateRetrievalUrlRequest], + Awaitable[warehouse.GenerateRetrievalUrlResponse]]: + r"""Return a callable for the generate retrieval url method over gRPC. + + Generates a signed url for downloading the asset. + For video warehouse, please see comment of UploadAsset + about how to allow retrieval of cloud storage files in a + different project. + + Returns: + Callable[[~.GenerateRetrievalUrlRequest], + Awaitable[~.GenerateRetrievalUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_retrieval_url' not in self._stubs: + self._stubs['generate_retrieval_url'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GenerateRetrievalUrl', + request_serializer=warehouse.GenerateRetrievalUrlRequest.serialize, + response_deserializer=warehouse.GenerateRetrievalUrlResponse.deserialize, + ) + return self._stubs['generate_retrieval_url'] + + @property + def analyze_asset(self) -> Callable[ + [warehouse.AnalyzeAssetRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the analyze asset method over gRPC. + + Analyze asset to power search capability. + + Returns: + Callable[[~.AnalyzeAssetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_asset' not in self._stubs: + self._stubs['analyze_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/AnalyzeAsset', + request_serializer=warehouse.AnalyzeAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['analyze_asset'] + + @property + def index_asset(self) -> Callable[ + [warehouse.IndexAssetRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the index asset method over gRPC. + + Index one asset for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + Returns: + Callable[[~.IndexAssetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'index_asset' not in self._stubs: + self._stubs['index_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/IndexAsset', + request_serializer=warehouse.IndexAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['index_asset'] + + @property + def remove_index_asset(self) -> Callable[ + [warehouse.RemoveIndexAssetRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove index asset method over gRPC. + + Remove one asset's index data for search. Supported corpus type: + Corpus.Type.VIDEO_ON_DEMAND + + Returns: + Callable[[~.RemoveIndexAssetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_index_asset' not in self._stubs: + self._stubs['remove_index_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/RemoveIndexAsset', + request_serializer=warehouse.RemoveIndexAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_index_asset'] + + @property + def view_indexed_assets(self) -> Callable[ + [warehouse.ViewIndexedAssetsRequest], + Awaitable[warehouse.ViewIndexedAssetsResponse]]: + r"""Return a callable for the view indexed assets method over gRPC. + + Lists assets inside an index. + + Returns: + Callable[[~.ViewIndexedAssetsRequest], + Awaitable[~.ViewIndexedAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'view_indexed_assets' not in self._stubs: + self._stubs['view_indexed_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ViewIndexedAssets', + request_serializer=warehouse.ViewIndexedAssetsRequest.serialize, + response_deserializer=warehouse.ViewIndexedAssetsResponse.deserialize, + ) + return self._stubs['view_indexed_assets'] + + @property + def create_index(self) -> Callable[ + [warehouse.CreateIndexRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create index method over gRPC. + + Creates an Index under the corpus. + + Returns: + Callable[[~.CreateIndexRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_index' not in self._stubs: + self._stubs['create_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateIndex', + request_serializer=warehouse.CreateIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_index'] + + @property + def update_index(self) -> Callable[ + [warehouse.UpdateIndexRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update index method over gRPC. + + Updates an Index under the corpus. Users can perform a + metadata-only update or trigger a full index rebuild with + different update_mask values. + + Returns: + Callable[[~.UpdateIndexRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_index' not in self._stubs: + self._stubs['update_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateIndex', + request_serializer=warehouse.UpdateIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_index'] + + @property + def get_index(self) -> Callable[ + [warehouse.GetIndexRequest], + Awaitable[warehouse.Index]]: + r"""Return a callable for the get index method over gRPC. + + Gets the details of a single Index under a Corpus. + + Returns: + Callable[[~.GetIndexRequest], + Awaitable[~.Index]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_index' not in self._stubs: + self._stubs['get_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetIndex', + request_serializer=warehouse.GetIndexRequest.serialize, + response_deserializer=warehouse.Index.deserialize, + ) + return self._stubs['get_index'] + + @property + def list_indexes(self) -> Callable[ + [warehouse.ListIndexesRequest], + Awaitable[warehouse.ListIndexesResponse]]: + r"""Return a callable for the list indexes method over gRPC. + + List all Indexes in a given Corpus. + + Returns: + Callable[[~.ListIndexesRequest], + Awaitable[~.ListIndexesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_indexes' not in self._stubs: + self._stubs['list_indexes'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListIndexes', + request_serializer=warehouse.ListIndexesRequest.serialize, + response_deserializer=warehouse.ListIndexesResponse.deserialize, + ) + return self._stubs['list_indexes'] + + @property + def delete_index(self) -> Callable[ + [warehouse.DeleteIndexRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete index method over gRPC. + + Delete a single Index. In order to delete an index, + the caller must make sure that it is not deployed to any + index endpoint. + + Returns: + Callable[[~.DeleteIndexRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_index' not in self._stubs: + self._stubs['delete_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteIndex', + request_serializer=warehouse.DeleteIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_index'] + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create corpus method over gRPC. + + Creates a corpus inside a project. + + Returns: + Callable[[~.CreateCorpusRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_corpus' not in self._stubs: + self._stubs['create_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateCorpus', + request_serializer=warehouse.CreateCorpusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_corpus'] + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + Awaitable[warehouse.Corpus]]: + r"""Return a callable for the get corpus method over gRPC. + + Gets corpus details inside a project. + + Returns: + Callable[[~.GetCorpusRequest], + Awaitable[~.Corpus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['get_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetCorpus', + request_serializer=warehouse.GetCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['get_corpus'] + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + Awaitable[warehouse.Corpus]]: + r"""Return a callable for the update corpus method over gRPC. + + Updates a corpus in a project. + + Returns: + Callable[[~.UpdateCorpusRequest], + Awaitable[~.Corpus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['update_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateCorpus', + request_serializer=warehouse.UpdateCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['update_corpus'] + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + Awaitable[warehouse.ListCorporaResponse]]: + r"""Return a callable for the list corpora method over gRPC. + + Lists all corpora in a project. + + Returns: + Callable[[~.ListCorporaRequest], + Awaitable[~.ListCorporaResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpora' not in self._stubs: + self._stubs['list_corpora'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListCorpora', + request_serializer=warehouse.ListCorporaRequest.serialize, + response_deserializer=warehouse.ListCorporaResponse.deserialize, + ) + return self._stubs['list_corpora'] + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete corpus method over gRPC. + + Deletes a corpus only if its empty. + Returns empty response. + + Returns: + Callable[[~.DeleteCorpusRequest], + 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_corpus' not in self._stubs: + self._stubs['delete_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteCorpus', + request_serializer=warehouse.DeleteCorpusRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_corpus'] + + @property + def analyze_corpus(self) -> Callable[ + [warehouse.AnalyzeCorpusRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the analyze corpus method over gRPC. + + Analyzes a corpus. + + Returns: + Callable[[~.AnalyzeCorpusRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_corpus' not in self._stubs: + self._stubs['analyze_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/AnalyzeCorpus', + request_serializer=warehouse.AnalyzeCorpusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['analyze_corpus'] + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + Awaitable[warehouse.DataSchema]]: + r"""Return a callable for the create data schema method over gRPC. + + Creates data schema inside corpus. + + Returns: + Callable[[~.CreateDataSchemaRequest], + Awaitable[~.DataSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['create_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateDataSchema', + request_serializer=warehouse.CreateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['create_data_schema'] + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + Awaitable[warehouse.DataSchema]]: + r"""Return a callable for the update data schema method over gRPC. + + Updates data schema inside corpus. + + Returns: + Callable[[~.UpdateDataSchemaRequest], + Awaitable[~.DataSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['update_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateDataSchema', + request_serializer=warehouse.UpdateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['update_data_schema'] + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + Awaitable[warehouse.DataSchema]]: + r"""Return a callable for the get data schema method over gRPC. + + Gets data schema inside corpus. + + Returns: + Callable[[~.GetDataSchemaRequest], + Awaitable[~.DataSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['get_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetDataSchema', + request_serializer=warehouse.GetDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['get_data_schema'] + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete data schema method over gRPC. + + Deletes data schema inside corpus. + + Returns: + Callable[[~.DeleteDataSchemaRequest], + 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_data_schema' not in self._stubs: + self._stubs['delete_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteDataSchema', + request_serializer=warehouse.DeleteDataSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_schema'] + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + Awaitable[warehouse.ListDataSchemasResponse]]: + r"""Return a callable for the list data schemas method over gRPC. + + Lists a list of data schemas inside corpus. + + Returns: + Callable[[~.ListDataSchemasRequest], + Awaitable[~.ListDataSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schemas' not in self._stubs: + self._stubs['list_data_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListDataSchemas', + request_serializer=warehouse.ListDataSchemasRequest.serialize, + response_deserializer=warehouse.ListDataSchemasResponse.deserialize, + ) + return self._stubs['list_data_schemas'] + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + Awaitable[warehouse.Annotation]]: + r"""Return a callable for the create annotation method over gRPC. + + Creates annotation inside asset. + + Returns: + Callable[[~.CreateAnnotationRequest], + Awaitable[~.Annotation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['create_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateAnnotation', + request_serializer=warehouse.CreateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['create_annotation'] + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + Awaitable[warehouse.Annotation]]: + r"""Return a callable for the get annotation method over gRPC. + + Reads annotation inside asset. + + Returns: + Callable[[~.GetAnnotationRequest], + Awaitable[~.Annotation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['get_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetAnnotation', + request_serializer=warehouse.GetAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['get_annotation'] + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + Awaitable[warehouse.ListAnnotationsResponse]]: + r"""Return a callable for the list annotations method over gRPC. + + Lists a list of annotations inside asset. + + Returns: + Callable[[~.ListAnnotationsRequest], + Awaitable[~.ListAnnotationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotations' not in self._stubs: + self._stubs['list_annotations'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListAnnotations', + request_serializer=warehouse.ListAnnotationsRequest.serialize, + response_deserializer=warehouse.ListAnnotationsResponse.deserialize, + ) + return self._stubs['list_annotations'] + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + Awaitable[warehouse.Annotation]]: + r"""Return a callable for the update annotation method over gRPC. + + Updates annotation inside asset. + + Returns: + Callable[[~.UpdateAnnotationRequest], + Awaitable[~.Annotation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['update_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateAnnotation', + request_serializer=warehouse.UpdateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['update_annotation'] + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete annotation method over gRPC. + + Deletes annotation inside asset. + + Returns: + Callable[[~.DeleteAnnotationRequest], + 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_annotation' not in self._stubs: + self._stubs['delete_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteAnnotation', + request_serializer=warehouse.DeleteAnnotationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotation'] + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + Awaitable[warehouse.IngestAssetResponse]]: + r"""Return a callable for the ingest asset method over gRPC. + + Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + Returns: + Callable[[~.IngestAssetRequest], + Awaitable[~.IngestAssetResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'ingest_asset' not in self._stubs: + self._stubs['ingest_asset'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1.Warehouse/IngestAsset', + request_serializer=warehouse.IngestAssetRequest.serialize, + response_deserializer=warehouse.IngestAssetResponse.deserialize, + ) + return self._stubs['ingest_asset'] + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + Awaitable[warehouse.ClipAssetResponse]]: + r"""Return a callable for the clip asset method over gRPC. + + Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + Returns: + Callable[[~.ClipAssetRequest], + Awaitable[~.ClipAssetResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'clip_asset' not in self._stubs: + self._stubs['clip_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ClipAsset', + request_serializer=warehouse.ClipAssetRequest.serialize, + response_deserializer=warehouse.ClipAssetResponse.deserialize, + ) + return self._stubs['clip_asset'] + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + Awaitable[warehouse.GenerateHlsUriResponse]]: + r"""Return a callable for the generate hls uri method over gRPC. + + Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + Returns: + Callable[[~.GenerateHlsUriRequest], + Awaitable[~.GenerateHlsUriResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_hls_uri' not in self._stubs: + self._stubs['generate_hls_uri'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GenerateHlsUri', + request_serializer=warehouse.GenerateHlsUriRequest.serialize, + response_deserializer=warehouse.GenerateHlsUriResponse.deserialize, + ) + return self._stubs['generate_hls_uri'] + + @property + def import_assets(self) -> Callable[ + [warehouse.ImportAssetsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import assets method over gRPC. + + Imports assets (images plus annotations) from a meta + file on cloud storage. Each row in the meta file is + corresponding to an image (specified by a cloud storage + uri) and its annotations. + + Returns: + Callable[[~.ImportAssetsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_assets' not in self._stubs: + self._stubs['import_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ImportAssets', + request_serializer=warehouse.ImportAssetsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_assets'] + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + Awaitable[warehouse.SearchConfig]]: + r"""Return a callable for the create search config method over gRPC. + + Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.CreateSearchConfigRequest], + Awaitable[~.SearchConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['create_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateSearchConfig', + request_serializer=warehouse.CreateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['create_search_config'] + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + Awaitable[warehouse.SearchConfig]]: + r"""Return a callable for the update search config method over gRPC. + + Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.UpdateSearchConfigRequest], + Awaitable[~.SearchConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['update_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateSearchConfig', + request_serializer=warehouse.UpdateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['update_search_config'] + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + Awaitable[warehouse.SearchConfig]]: + r"""Return a callable for the get search config method over gRPC. + + Gets a search configuration inside a corpus. + + Returns: + Callable[[~.GetSearchConfigRequest], + Awaitable[~.SearchConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['get_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetSearchConfig', + request_serializer=warehouse.GetSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['get_search_config'] + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete search config method over gRPC. + + Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + Returns: + Callable[[~.DeleteSearchConfigRequest], + 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_search_config' not in self._stubs: + self._stubs['delete_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteSearchConfig', + request_serializer=warehouse.DeleteSearchConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_config'] + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + Awaitable[warehouse.ListSearchConfigsResponse]]: + r"""Return a callable for the list search configs method over gRPC. + + Lists all search configurations inside a corpus. + + Returns: + Callable[[~.ListSearchConfigsRequest], + Awaitable[~.ListSearchConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_configs' not in self._stubs: + self._stubs['list_search_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListSearchConfigs', + request_serializer=warehouse.ListSearchConfigsRequest.serialize, + response_deserializer=warehouse.ListSearchConfigsResponse.deserialize, + ) + return self._stubs['list_search_configs'] + + @property + def create_search_hypernym(self) -> Callable[ + [warehouse.CreateSearchHypernymRequest], + Awaitable[warehouse.SearchHypernym]]: + r"""Return a callable for the create search hypernym method over gRPC. + + Creates a SearchHypernym inside a corpus. + + Returns: + Callable[[~.CreateSearchHypernymRequest], + Awaitable[~.SearchHypernym]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernym' not in self._stubs: + self._stubs['create_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateSearchHypernym', + request_serializer=warehouse.CreateSearchHypernymRequest.serialize, + response_deserializer=warehouse.SearchHypernym.deserialize, + ) + return self._stubs['create_search_hypernym'] + + @property + def update_search_hypernym(self) -> Callable[ + [warehouse.UpdateSearchHypernymRequest], + Awaitable[warehouse.SearchHypernym]]: + r"""Return a callable for the update search hypernym method over gRPC. + + Updates a SearchHypernym inside a corpus. + + Returns: + Callable[[~.UpdateSearchHypernymRequest], + Awaitable[~.SearchHypernym]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernym' not in self._stubs: + self._stubs['update_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateSearchHypernym', + request_serializer=warehouse.UpdateSearchHypernymRequest.serialize, + response_deserializer=warehouse.SearchHypernym.deserialize, + ) + return self._stubs['update_search_hypernym'] + + @property + def get_search_hypernym(self) -> Callable[ + [warehouse.GetSearchHypernymRequest], + Awaitable[warehouse.SearchHypernym]]: + r"""Return a callable for the get search hypernym method over gRPC. + + Gets a SearchHypernym inside a corpus. + + Returns: + Callable[[~.GetSearchHypernymRequest], + Awaitable[~.SearchHypernym]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernym' not in self._stubs: + self._stubs['get_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetSearchHypernym', + request_serializer=warehouse.GetSearchHypernymRequest.serialize, + response_deserializer=warehouse.SearchHypernym.deserialize, + ) + return self._stubs['get_search_hypernym'] + + @property + def delete_search_hypernym(self) -> Callable[ + [warehouse.DeleteSearchHypernymRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete search hypernym method over gRPC. + + Deletes a SearchHypernym inside a corpus. + + Returns: + Callable[[~.DeleteSearchHypernymRequest], + 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_search_hypernym' not in self._stubs: + self._stubs['delete_search_hypernym'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteSearchHypernym', + request_serializer=warehouse.DeleteSearchHypernymRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_hypernym'] + + @property + def list_search_hypernyms(self) -> Callable[ + [warehouse.ListSearchHypernymsRequest], + Awaitable[warehouse.ListSearchHypernymsResponse]]: + r"""Return a callable for the list search hypernyms method over gRPC. + + Lists SearchHypernyms inside a corpus. + + Returns: + Callable[[~.ListSearchHypernymsRequest], + Awaitable[~.ListSearchHypernymsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_hypernyms' not in self._stubs: + self._stubs['list_search_hypernyms'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListSearchHypernyms', + request_serializer=warehouse.ListSearchHypernymsRequest.serialize, + response_deserializer=warehouse.ListSearchHypernymsResponse.deserialize, + ) + return self._stubs['list_search_hypernyms'] + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + Awaitable[warehouse.SearchAssetsResponse]]: + r"""Return a callable for the search assets method over gRPC. + + Search media asset. + + Returns: + Callable[[~.SearchAssetsRequest], + Awaitable[~.SearchAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_assets' not in self._stubs: + self._stubs['search_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/SearchAssets', + request_serializer=warehouse.SearchAssetsRequest.serialize, + response_deserializer=warehouse.SearchAssetsResponse.deserialize, + ) + return self._stubs['search_assets'] + + @property + def search_index_endpoint(self) -> Callable[ + [warehouse.SearchIndexEndpointRequest], + Awaitable[warehouse.SearchIndexEndpointResponse]]: + r"""Return a callable for the search index endpoint method over gRPC. + + Search a deployed index endpoint (IMAGE corpus type + only). + + Returns: + Callable[[~.SearchIndexEndpointRequest], + Awaitable[~.SearchIndexEndpointResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_index_endpoint' not in self._stubs: + self._stubs['search_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/SearchIndexEndpoint', + request_serializer=warehouse.SearchIndexEndpointRequest.serialize, + response_deserializer=warehouse.SearchIndexEndpointResponse.deserialize, + ) + return self._stubs['search_index_endpoint'] + + @property + def create_index_endpoint(self) -> Callable[ + [warehouse.CreateIndexEndpointRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create index endpoint method over gRPC. + + Creates an IndexEndpoint. + + Returns: + Callable[[~.CreateIndexEndpointRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_index_endpoint' not in self._stubs: + self._stubs['create_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateIndexEndpoint', + request_serializer=warehouse.CreateIndexEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_index_endpoint'] + + @property + def get_index_endpoint(self) -> Callable[ + [warehouse.GetIndexEndpointRequest], + Awaitable[warehouse.IndexEndpoint]]: + r"""Return a callable for the get index endpoint method over gRPC. + + Gets an IndexEndpoint. + + Returns: + Callable[[~.GetIndexEndpointRequest], + Awaitable[~.IndexEndpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_index_endpoint' not in self._stubs: + self._stubs['get_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetIndexEndpoint', + request_serializer=warehouse.GetIndexEndpointRequest.serialize, + response_deserializer=warehouse.IndexEndpoint.deserialize, + ) + return self._stubs['get_index_endpoint'] + + @property + def list_index_endpoints(self) -> Callable[ + [warehouse.ListIndexEndpointsRequest], + Awaitable[warehouse.ListIndexEndpointsResponse]]: + r"""Return a callable for the list index endpoints method over gRPC. + + Lists all IndexEndpoints in a project. + + Returns: + Callable[[~.ListIndexEndpointsRequest], + Awaitable[~.ListIndexEndpointsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_index_endpoints' not in self._stubs: + self._stubs['list_index_endpoints'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListIndexEndpoints', + request_serializer=warehouse.ListIndexEndpointsRequest.serialize, + response_deserializer=warehouse.ListIndexEndpointsResponse.deserialize, + ) + return self._stubs['list_index_endpoints'] + + @property + def update_index_endpoint(self) -> Callable[ + [warehouse.UpdateIndexEndpointRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update index endpoint method over gRPC. + + Updates an IndexEndpoint. + + Returns: + Callable[[~.UpdateIndexEndpointRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_index_endpoint' not in self._stubs: + self._stubs['update_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateIndexEndpoint', + request_serializer=warehouse.UpdateIndexEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_index_endpoint'] + + @property + def delete_index_endpoint(self) -> Callable[ + [warehouse.DeleteIndexEndpointRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete index endpoint method over gRPC. + + Deletes an IndexEndpoint. + + Returns: + Callable[[~.DeleteIndexEndpointRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_index_endpoint' not in self._stubs: + self._stubs['delete_index_endpoint'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteIndexEndpoint', + request_serializer=warehouse.DeleteIndexEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_index_endpoint'] + + @property + def deploy_index(self) -> Callable[ + [warehouse.DeployIndexRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the deploy index method over gRPC. + + Deploys an Index to IndexEndpoint. + + Returns: + Callable[[~.DeployIndexRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_index' not in self._stubs: + self._stubs['deploy_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeployIndex', + request_serializer=warehouse.DeployIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_index'] + + @property + def undeploy_index(self) -> Callable[ + [warehouse.UndeployIndexRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the undeploy index method over gRPC. + + Undeploys an Index from IndexEndpoint. + + Returns: + Callable[[~.UndeployIndexRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undeploy_index' not in self._stubs: + self._stubs['undeploy_index'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UndeployIndex', + request_serializer=warehouse.UndeployIndexRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_index'] + + @property + def create_collection(self) -> Callable[ + [warehouse.CreateCollectionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create collection method over gRPC. + + Creates a collection. + + Returns: + Callable[[~.CreateCollectionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_collection' not in self._stubs: + self._stubs['create_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/CreateCollection', + request_serializer=warehouse.CreateCollectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_collection'] + + @property + def delete_collection(self) -> Callable[ + [warehouse.DeleteCollectionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete collection method over gRPC. + + Deletes a collection. + + Returns: + Callable[[~.DeleteCollectionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_collection' not in self._stubs: + self._stubs['delete_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/DeleteCollection', + request_serializer=warehouse.DeleteCollectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_collection'] + + @property + def get_collection(self) -> Callable[ + [warehouse.GetCollectionRequest], + Awaitable[warehouse.Collection]]: + r"""Return a callable for the get collection method over gRPC. + + Gets a collection. + + Returns: + Callable[[~.GetCollectionRequest], + Awaitable[~.Collection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_collection' not in self._stubs: + self._stubs['get_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/GetCollection', + request_serializer=warehouse.GetCollectionRequest.serialize, + response_deserializer=warehouse.Collection.deserialize, + ) + return self._stubs['get_collection'] + + @property + def update_collection(self) -> Callable[ + [warehouse.UpdateCollectionRequest], + Awaitable[warehouse.Collection]]: + r"""Return a callable for the update collection method over gRPC. + + Updates a collection. + + Returns: + Callable[[~.UpdateCollectionRequest], + Awaitable[~.Collection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_collection' not in self._stubs: + self._stubs['update_collection'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/UpdateCollection', + request_serializer=warehouse.UpdateCollectionRequest.serialize, + response_deserializer=warehouse.Collection.deserialize, + ) + return self._stubs['update_collection'] + + @property + def list_collections(self) -> Callable[ + [warehouse.ListCollectionsRequest], + Awaitable[warehouse.ListCollectionsResponse]]: + r"""Return a callable for the list collections method over gRPC. + + Lists collections inside a corpus. + + Returns: + Callable[[~.ListCollectionsRequest], + Awaitable[~.ListCollectionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_collections' not in self._stubs: + self._stubs['list_collections'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ListCollections', + request_serializer=warehouse.ListCollectionsRequest.serialize, + response_deserializer=warehouse.ListCollectionsResponse.deserialize, + ) + return self._stubs['list_collections'] + + @property + def add_collection_item(self) -> Callable[ + [warehouse.AddCollectionItemRequest], + Awaitable[warehouse.AddCollectionItemResponse]]: + r"""Return a callable for the add collection item method over gRPC. + + Adds an item into a Collection. + + Returns: + Callable[[~.AddCollectionItemRequest], + Awaitable[~.AddCollectionItemResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_collection_item' not in self._stubs: + self._stubs['add_collection_item'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/AddCollectionItem', + request_serializer=warehouse.AddCollectionItemRequest.serialize, + response_deserializer=warehouse.AddCollectionItemResponse.deserialize, + ) + return self._stubs['add_collection_item'] + + @property + def remove_collection_item(self) -> Callable[ + [warehouse.RemoveCollectionItemRequest], + Awaitable[warehouse.RemoveCollectionItemResponse]]: + r"""Return a callable for the remove collection item method over gRPC. + + Removes an item from a collection. + + Returns: + Callable[[~.RemoveCollectionItemRequest], + Awaitable[~.RemoveCollectionItemResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_collection_item' not in self._stubs: + self._stubs['remove_collection_item'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/RemoveCollectionItem', + request_serializer=warehouse.RemoveCollectionItemRequest.serialize, + response_deserializer=warehouse.RemoveCollectionItemResponse.deserialize, + ) + return self._stubs['remove_collection_item'] + + @property + def view_collection_items(self) -> Callable[ + [warehouse.ViewCollectionItemsRequest], + Awaitable[warehouse.ViewCollectionItemsResponse]]: + r"""Return a callable for the view collection items method over gRPC. + + View items inside a collection. + + Returns: + Callable[[~.ViewCollectionItemsRequest], + Awaitable[~.ViewCollectionItemsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'view_collection_items' not in self._stubs: + self._stubs['view_collection_items'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1.Warehouse/ViewCollectionItems', + request_serializer=warehouse.ViewCollectionItemsRequest.serialize, + response_deserializer=warehouse.ViewCollectionItemsResponse.deserialize, + ) + return self._stubs['view_collection_items'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_asset: gapic_v1.method_async.wrap_method( + self.create_asset, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_asset: gapic_v1.method_async.wrap_method( + self.update_asset, + default_timeout=None, + client_info=client_info, + ), + self.get_asset: gapic_v1.method_async.wrap_method( + self.get_asset, + default_timeout=None, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + default_timeout=None, + client_info=client_info, + ), + self.delete_asset: gapic_v1.method_async.wrap_method( + self.delete_asset, + default_timeout=None, + client_info=client_info, + ), + self.upload_asset: gapic_v1.method_async.wrap_method( + self.upload_asset, + default_timeout=None, + client_info=client_info, + ), + self.generate_retrieval_url: gapic_v1.method_async.wrap_method( + self.generate_retrieval_url, + default_timeout=None, + client_info=client_info, + ), + self.analyze_asset: gapic_v1.method_async.wrap_method( + self.analyze_asset, + default_timeout=None, + client_info=client_info, + ), + self.index_asset: gapic_v1.method_async.wrap_method( + self.index_asset, + default_timeout=None, + client_info=client_info, + ), + self.remove_index_asset: gapic_v1.method_async.wrap_method( + self.remove_index_asset, + default_timeout=None, + client_info=client_info, + ), + self.view_indexed_assets: gapic_v1.method_async.wrap_method( + self.view_indexed_assets, + default_timeout=None, + client_info=client_info, + ), + self.create_index: gapic_v1.method_async.wrap_method( + self.create_index, + default_timeout=None, + client_info=client_info, + ), + self.update_index: gapic_v1.method_async.wrap_method( + self.update_index, + default_timeout=None, + client_info=client_info, + ), + self.get_index: gapic_v1.method_async.wrap_method( + self.get_index, + default_timeout=None, + client_info=client_info, + ), + self.list_indexes: gapic_v1.method_async.wrap_method( + self.list_indexes, + default_timeout=None, + client_info=client_info, + ), + self.delete_index: gapic_v1.method_async.wrap_method( + self.delete_index, + default_timeout=None, + client_info=client_info, + ), + self.create_corpus: gapic_v1.method_async.wrap_method( + self.create_corpus, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_corpus: gapic_v1.method_async.wrap_method( + self.get_corpus, + default_timeout=None, + client_info=client_info, + ), + self.update_corpus: gapic_v1.method_async.wrap_method( + self.update_corpus, + default_timeout=None, + client_info=client_info, + ), + self.list_corpora: gapic_v1.method_async.wrap_method( + self.list_corpora, + default_timeout=None, + client_info=client_info, + ), + self.delete_corpus: gapic_v1.method_async.wrap_method( + self.delete_corpus, + default_timeout=None, + client_info=client_info, + ), + self.analyze_corpus: gapic_v1.method_async.wrap_method( + self.analyze_corpus, + default_timeout=None, + client_info=client_info, + ), + self.create_data_schema: gapic_v1.method_async.wrap_method( + self.create_data_schema, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_data_schema: gapic_v1.method_async.wrap_method( + self.update_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.get_data_schema: gapic_v1.method_async.wrap_method( + self.get_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_schema: gapic_v1.method_async.wrap_method( + self.delete_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_data_schemas: gapic_v1.method_async.wrap_method( + self.list_data_schemas, + default_timeout=None, + client_info=client_info, + ), + self.create_annotation: gapic_v1.method_async.wrap_method( + self.create_annotation, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_annotation: gapic_v1.method_async.wrap_method( + self.get_annotation, + default_timeout=None, + client_info=client_info, + ), + self.list_annotations: gapic_v1.method_async.wrap_method( + self.list_annotations, + default_timeout=None, + client_info=client_info, + ), + self.update_annotation: gapic_v1.method_async.wrap_method( + self.update_annotation, + default_timeout=None, + client_info=client_info, + ), + self.delete_annotation: gapic_v1.method_async.wrap_method( + self.delete_annotation, + default_timeout=None, + client_info=client_info, + ), + self.ingest_asset: gapic_v1.method_async.wrap_method( + self.ingest_asset, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.clip_asset: gapic_v1.method_async.wrap_method( + self.clip_asset, + default_timeout=None, + client_info=client_info, + ), + self.generate_hls_uri: gapic_v1.method_async.wrap_method( + self.generate_hls_uri, + default_timeout=None, + client_info=client_info, + ), + self.import_assets: gapic_v1.method_async.wrap_method( + self.import_assets, + default_timeout=None, + client_info=client_info, + ), + self.create_search_config: gapic_v1.method_async.wrap_method( + self.create_search_config, + default_timeout=None, + client_info=client_info, + ), + self.update_search_config: gapic_v1.method_async.wrap_method( + self.update_search_config, + default_timeout=None, + client_info=client_info, + ), + self.get_search_config: gapic_v1.method_async.wrap_method( + self.get_search_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_config: gapic_v1.method_async.wrap_method( + self.delete_search_config, + default_timeout=None, + client_info=client_info, + ), + self.list_search_configs: gapic_v1.method_async.wrap_method( + self.list_search_configs, + default_timeout=None, + client_info=client_info, + ), + self.create_search_hypernym: gapic_v1.method_async.wrap_method( + self.create_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.update_search_hypernym: gapic_v1.method_async.wrap_method( + self.update_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.get_search_hypernym: gapic_v1.method_async.wrap_method( + self.get_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_hypernym: gapic_v1.method_async.wrap_method( + self.delete_search_hypernym, + default_timeout=None, + client_info=client_info, + ), + self.list_search_hypernyms: gapic_v1.method_async.wrap_method( + self.list_search_hypernyms, + default_timeout=None, + client_info=client_info, + ), + self.search_assets: gapic_v1.method_async.wrap_method( + self.search_assets, + default_timeout=None, + client_info=client_info, + ), + self.search_index_endpoint: gapic_v1.method_async.wrap_method( + self.search_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.create_index_endpoint: gapic_v1.method_async.wrap_method( + self.create_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.get_index_endpoint: gapic_v1.method_async.wrap_method( + self.get_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.list_index_endpoints: gapic_v1.method_async.wrap_method( + self.list_index_endpoints, + default_timeout=None, + client_info=client_info, + ), + self.update_index_endpoint: gapic_v1.method_async.wrap_method( + self.update_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.delete_index_endpoint: gapic_v1.method_async.wrap_method( + self.delete_index_endpoint, + default_timeout=None, + client_info=client_info, + ), + self.deploy_index: gapic_v1.method_async.wrap_method( + self.deploy_index, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_index: gapic_v1.method_async.wrap_method( + self.undeploy_index, + default_timeout=None, + client_info=client_info, + ), + self.create_collection: gapic_v1.method_async.wrap_method( + self.create_collection, + default_timeout=None, + client_info=client_info, + ), + self.delete_collection: gapic_v1.method_async.wrap_method( + self.delete_collection, + default_timeout=None, + client_info=client_info, + ), + self.get_collection: gapic_v1.method_async.wrap_method( + self.get_collection, + default_timeout=None, + client_info=client_info, + ), + self.update_collection: gapic_v1.method_async.wrap_method( + self.update_collection, + default_timeout=None, + client_info=client_info, + ), + self.list_collections: gapic_v1.method_async.wrap_method( + self.list_collections, + default_timeout=None, + client_info=client_info, + ), + self.add_collection_item: gapic_v1.method_async.wrap_method( + self.add_collection_item, + default_timeout=None, + client_info=client_info, + ), + self.remove_collection_item: gapic_v1.method_async.wrap_method( + self.remove_collection_item, + default_timeout=None, + client_info=client_info, + ), + self.view_collection_items: gapic_v1.method_async.wrap_method( + self.view_collection_items, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'WarehouseGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/rest.py new file mode 100644 index 000000000000..2ad907c0b25e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/services/warehouse/transports/rest.py @@ -0,0 +1,7691 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1.types import warehouse +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import WarehouseTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class WarehouseRestInterceptor: + """Interceptor for Warehouse. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the WarehouseRestTransport. + + .. code-block:: python + class MyCustomWarehouseInterceptor(WarehouseRestInterceptor): + def pre_add_collection_item(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_collection_item(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_clip_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_clip_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_annotation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_collection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_collection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_data_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_index(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_index(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_index_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_index_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_search_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_search_hypernym(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_search_hypernym(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_collection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_collection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_index(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_index(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_index_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_index_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_search_hypernym(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_deploy_index(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_deploy_index(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_hls_uri(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_hls_uri(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_retrieval_url(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_retrieval_url(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_annotation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_collection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_collection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_index(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_index(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_index_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_index_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_search_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_search_hypernym(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_search_hypernym(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_index_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_index_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_annotations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_annotations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_collections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_collections(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_corpora(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_corpora(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_schemas(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_schemas(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_index_endpoints(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_index_endpoints(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_indexes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_indexes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_search_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_search_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_search_hypernyms(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_search_hypernyms(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_collection_item(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_collection_item(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_index_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_index_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_index_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_index_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undeploy_index(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undeploy_index(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_annotation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_collection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_collection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_index(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_index(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_index_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_index_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_search_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_search_hypernym(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_search_hypernym(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_upload_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_upload_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_view_collection_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_view_collection_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_view_indexed_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_view_indexed_assets(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WarehouseRestTransport(interceptor=MyCustomWarehouseInterceptor()) + client = WarehouseClient(transport=transport) + + + """ + def pre_add_collection_item(self, request: warehouse.AddCollectionItemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.AddCollectionItemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for add_collection_item + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_add_collection_item(self, response: warehouse.AddCollectionItemResponse) -> warehouse.AddCollectionItemResponse: + """Post-rpc interceptor for add_collection_item + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_analyze_asset(self, request: warehouse.AnalyzeAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.AnalyzeAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_analyze_asset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for analyze_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_analyze_corpus(self, request: warehouse.AnalyzeCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.AnalyzeCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_analyze_corpus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for analyze_corpus + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_clip_asset(self, request: warehouse.ClipAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ClipAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for clip_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_clip_asset(self, response: warehouse.ClipAssetResponse) -> warehouse.ClipAssetResponse: + """Post-rpc interceptor for clip_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_annotation(self, request: warehouse.CreateAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_annotation(self, response: warehouse.Annotation) -> warehouse.Annotation: + """Post-rpc interceptor for create_annotation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_asset(self, request: warehouse.CreateAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_asset(self, response: warehouse.Asset) -> warehouse.Asset: + """Post-rpc interceptor for create_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_collection(self, request: warehouse.CreateCollectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateCollectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_collection + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_collection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_collection + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_corpus(self, request: warehouse.CreateCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_corpus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_corpus + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_data_schema(self, request: warehouse.CreateDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_data_schema(self, response: warehouse.DataSchema) -> warehouse.DataSchema: + """Post-rpc interceptor for create_data_schema + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_index(self, request: warehouse.CreateIndexRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateIndexRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_index + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_index(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_index + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_index_endpoint(self, request: warehouse.CreateIndexEndpointRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateIndexEndpointRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_index_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_index_endpoint(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_index_endpoint + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_search_config(self, request: warehouse.CreateSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_search_config(self, response: warehouse.SearchConfig) -> warehouse.SearchConfig: + """Post-rpc interceptor for create_search_config + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_search_hypernym(self, request: warehouse.CreateSearchHypernymRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateSearchHypernymRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_search_hypernym + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_search_hypernym(self, response: warehouse.SearchHypernym) -> warehouse.SearchHypernym: + """Post-rpc interceptor for create_search_hypernym + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_annotation(self, request: warehouse.DeleteAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_delete_asset(self, request: warehouse.DeleteAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_delete_asset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_collection(self, request: warehouse.DeleteCollectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteCollectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_collection + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_delete_collection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_collection + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_corpus(self, request: warehouse.DeleteCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_delete_data_schema(self, request: warehouse.DeleteDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_delete_index(self, request: warehouse.DeleteIndexRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteIndexRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_index + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_delete_index(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_index + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_index_endpoint(self, request: warehouse.DeleteIndexEndpointRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteIndexEndpointRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_index_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_delete_index_endpoint(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_index_endpoint + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_search_config(self, request: warehouse.DeleteSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_delete_search_hypernym(self, request: warehouse.DeleteSearchHypernymRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteSearchHypernymRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_search_hypernym + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_deploy_index(self, request: warehouse.DeployIndexRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeployIndexRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for deploy_index + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_deploy_index(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for deploy_index + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_generate_hls_uri(self, request: warehouse.GenerateHlsUriRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GenerateHlsUriRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_hls_uri + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_generate_hls_uri(self, response: warehouse.GenerateHlsUriResponse) -> warehouse.GenerateHlsUriResponse: + """Post-rpc interceptor for generate_hls_uri + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_generate_retrieval_url(self, request: warehouse.GenerateRetrievalUrlRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GenerateRetrievalUrlRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_retrieval_url + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_generate_retrieval_url(self, response: warehouse.GenerateRetrievalUrlResponse) -> warehouse.GenerateRetrievalUrlResponse: + """Post-rpc interceptor for generate_retrieval_url + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_annotation(self, request: warehouse.GetAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_annotation(self, response: warehouse.Annotation) -> warehouse.Annotation: + """Post-rpc interceptor for get_annotation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_asset(self, request: warehouse.GetAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_asset(self, response: warehouse.Asset) -> warehouse.Asset: + """Post-rpc interceptor for get_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_collection(self, request: warehouse.GetCollectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetCollectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_collection + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_collection(self, response: warehouse.Collection) -> warehouse.Collection: + """Post-rpc interceptor for get_collection + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_corpus(self, request: warehouse.GetCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_corpus(self, response: warehouse.Corpus) -> warehouse.Corpus: + """Post-rpc interceptor for get_corpus + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_data_schema(self, request: warehouse.GetDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_data_schema(self, response: warehouse.DataSchema) -> warehouse.DataSchema: + """Post-rpc interceptor for get_data_schema + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_index(self, request: warehouse.GetIndexRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetIndexRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_index + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_index(self, response: warehouse.Index) -> warehouse.Index: + """Post-rpc interceptor for get_index + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_index_endpoint(self, request: warehouse.GetIndexEndpointRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetIndexEndpointRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_index_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_index_endpoint(self, response: warehouse.IndexEndpoint) -> warehouse.IndexEndpoint: + """Post-rpc interceptor for get_index_endpoint + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_search_config(self, request: warehouse.GetSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_search_config(self, response: warehouse.SearchConfig) -> warehouse.SearchConfig: + """Post-rpc interceptor for get_search_config + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_search_hypernym(self, request: warehouse.GetSearchHypernymRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetSearchHypernymRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_search_hypernym + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_search_hypernym(self, response: warehouse.SearchHypernym) -> warehouse.SearchHypernym: + """Post-rpc interceptor for get_search_hypernym + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_import_assets(self, request: warehouse.ImportAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ImportAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_import_assets(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_assets + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_index_asset(self, request: warehouse.IndexAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.IndexAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for index_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_index_asset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for index_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_annotations(self, request: warehouse.ListAnnotationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListAnnotationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_annotations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_annotations(self, response: warehouse.ListAnnotationsResponse) -> warehouse.ListAnnotationsResponse: + """Post-rpc interceptor for list_annotations + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: warehouse.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_assets(self, response: warehouse.ListAssetsResponse) -> warehouse.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_collections(self, request: warehouse.ListCollectionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListCollectionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_collections + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_collections(self, response: warehouse.ListCollectionsResponse) -> warehouse.ListCollectionsResponse: + """Post-rpc interceptor for list_collections + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_corpora(self, request: warehouse.ListCorporaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListCorporaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_corpora + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_corpora(self, response: warehouse.ListCorporaResponse) -> warehouse.ListCorporaResponse: + """Post-rpc interceptor for list_corpora + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_data_schemas(self, request: warehouse.ListDataSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListDataSchemasRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_data_schemas + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_data_schemas(self, response: warehouse.ListDataSchemasResponse) -> warehouse.ListDataSchemasResponse: + """Post-rpc interceptor for list_data_schemas + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_index_endpoints(self, request: warehouse.ListIndexEndpointsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListIndexEndpointsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_index_endpoints + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_index_endpoints(self, response: warehouse.ListIndexEndpointsResponse) -> warehouse.ListIndexEndpointsResponse: + """Post-rpc interceptor for list_index_endpoints + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_indexes(self, request: warehouse.ListIndexesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListIndexesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_indexes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_indexes(self, response: warehouse.ListIndexesResponse) -> warehouse.ListIndexesResponse: + """Post-rpc interceptor for list_indexes + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_search_configs(self, request: warehouse.ListSearchConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListSearchConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_search_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_search_configs(self, response: warehouse.ListSearchConfigsResponse) -> warehouse.ListSearchConfigsResponse: + """Post-rpc interceptor for list_search_configs + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_search_hypernyms(self, request: warehouse.ListSearchHypernymsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListSearchHypernymsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_search_hypernyms + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_search_hypernyms(self, response: warehouse.ListSearchHypernymsResponse) -> warehouse.ListSearchHypernymsResponse: + """Post-rpc interceptor for list_search_hypernyms + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_remove_collection_item(self, request: warehouse.RemoveCollectionItemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.RemoveCollectionItemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for remove_collection_item + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_remove_collection_item(self, response: warehouse.RemoveCollectionItemResponse) -> warehouse.RemoveCollectionItemResponse: + """Post-rpc interceptor for remove_collection_item + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_remove_index_asset(self, request: warehouse.RemoveIndexAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.RemoveIndexAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for remove_index_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_remove_index_asset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for remove_index_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_search_assets(self, request: warehouse.SearchAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.SearchAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_search_assets(self, response: warehouse.SearchAssetsResponse) -> warehouse.SearchAssetsResponse: + """Post-rpc interceptor for search_assets + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_search_index_endpoint(self, request: warehouse.SearchIndexEndpointRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.SearchIndexEndpointRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_index_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_search_index_endpoint(self, response: warehouse.SearchIndexEndpointResponse) -> warehouse.SearchIndexEndpointResponse: + """Post-rpc interceptor for search_index_endpoint + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_undeploy_index(self, request: warehouse.UndeployIndexRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UndeployIndexRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undeploy_index + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_undeploy_index(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for undeploy_index + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_annotation(self, request: warehouse.UpdateAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_annotation(self, response: warehouse.Annotation) -> warehouse.Annotation: + """Post-rpc interceptor for update_annotation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_asset(self, request: warehouse.UpdateAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_asset(self, response: warehouse.Asset) -> warehouse.Asset: + """Post-rpc interceptor for update_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_collection(self, request: warehouse.UpdateCollectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateCollectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_collection + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_collection(self, response: warehouse.Collection) -> warehouse.Collection: + """Post-rpc interceptor for update_collection + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_corpus(self, request: warehouse.UpdateCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_corpus(self, response: warehouse.Corpus) -> warehouse.Corpus: + """Post-rpc interceptor for update_corpus + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_data_schema(self, request: warehouse.UpdateDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_data_schema(self, response: warehouse.DataSchema) -> warehouse.DataSchema: + """Post-rpc interceptor for update_data_schema + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_index(self, request: warehouse.UpdateIndexRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateIndexRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_index + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_index(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_index + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_index_endpoint(self, request: warehouse.UpdateIndexEndpointRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateIndexEndpointRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_index_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_index_endpoint(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_index_endpoint + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_search_config(self, request: warehouse.UpdateSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_search_config(self, response: warehouse.SearchConfig) -> warehouse.SearchConfig: + """Post-rpc interceptor for update_search_config + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_search_hypernym(self, request: warehouse.UpdateSearchHypernymRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateSearchHypernymRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_search_hypernym + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_search_hypernym(self, response: warehouse.SearchHypernym) -> warehouse.SearchHypernym: + """Post-rpc interceptor for update_search_hypernym + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_upload_asset(self, request: warehouse.UploadAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UploadAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for upload_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_upload_asset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for upload_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_view_collection_items(self, request: warehouse.ViewCollectionItemsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ViewCollectionItemsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for view_collection_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_view_collection_items(self, response: warehouse.ViewCollectionItemsResponse) -> warehouse.ViewCollectionItemsResponse: + """Post-rpc interceptor for view_collection_items + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_view_indexed_assets(self, request: warehouse.ViewIndexedAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ViewIndexedAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for view_indexed_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_view_indexed_assets(self, response: warehouse.ViewIndexedAssetsResponse) -> warehouse.ViewIndexedAssetsResponse: + """Post-rpc interceptor for view_indexed_assets + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WarehouseRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WarehouseRestInterceptor + + +class WarehouseRestTransport(WarehouseTransport): + """REST backend transport for Warehouse. + + Service that manages media content + metadata for streaming. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[WarehouseRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or WarehouseRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _AddCollectionItem(WarehouseRestStub): + def __hash__(self): + return hash("AddCollectionItem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.AddCollectionItemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.AddCollectionItemResponse: + r"""Call the add collection item method over HTTP. + + Args: + request (~.warehouse.AddCollectionItemRequest): + The request object. Request message for + AddCollectionItem. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.AddCollectionItemResponse: + Response message for + AddCollectionItem. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{item.collection=projects/*/locations/*/corpora/*/collections/*}:addCollectionItem', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_add_collection_item(request, metadata) + pb_request = warehouse.AddCollectionItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.AddCollectionItemResponse() + pb_resp = warehouse.AddCollectionItemResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_add_collection_item(resp) + return resp + + class _AnalyzeAsset(WarehouseRestStub): + def __hash__(self): + return hash("AnalyzeAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.AnalyzeAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the analyze asset method over HTTP. + + Args: + request (~.warehouse.AnalyzeAssetRequest): + The request object. Request message for AnalyzeAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}:analyze', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_analyze_asset(request, metadata) + pb_request = warehouse.AnalyzeAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_asset(resp) + return resp + + class _AnalyzeCorpus(WarehouseRestStub): + def __hash__(self): + return hash("AnalyzeCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.AnalyzeCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the analyze corpus method over HTTP. + + Args: + request (~.warehouse.AnalyzeCorpusRequest): + The request object. Request message for AnalyzeCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*}:analyze', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_analyze_corpus(request, metadata) + pb_request = warehouse.AnalyzeCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_corpus(resp) + return resp + + class _ClipAsset(WarehouseRestStub): + def __hash__(self): + return hash("ClipAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ClipAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ClipAssetResponse: + r"""Call the clip asset method over HTTP. + + Args: + request (~.warehouse.ClipAssetRequest): + The request object. Request message for ClipAsset API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ClipAssetResponse: + Response message for ClipAsset API. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}:clip', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_clip_asset(request, metadata) + pb_request = warehouse.ClipAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ClipAssetResponse() + pb_resp = warehouse.ClipAssetResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_clip_asset(resp) + return resp + + class _CreateAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("CreateAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Annotation: + r"""Call the create annotation method over HTTP. + + Args: + request (~.warehouse.CreateAnnotationRequest): + The request object. Request message for CreateAnnotation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations', + 'body': 'annotation', + }, + ] + request, metadata = self._interceptor.pre_create_annotation(request, metadata) + pb_request = warehouse.CreateAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Annotation() + pb_resp = warehouse.Annotation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_annotation(resp) + return resp + + class _CreateAsset(WarehouseRestStub): + def __hash__(self): + return hash("CreateAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Asset: + r"""Call the create asset method over HTTP. + + Args: + request (~.warehouse.CreateAssetRequest): + The request object. Request message for + CreateAssetRequest. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/assets', + 'body': 'asset', + }, + ] + request, metadata = self._interceptor.pre_create_asset(request, metadata) + pb_request = warehouse.CreateAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Asset() + pb_resp = warehouse.Asset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_asset(resp) + return resp + + class _CreateCollection(WarehouseRestStub): + def __hash__(self): + return hash("CreateCollection") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateCollectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create collection method over HTTP. + + Args: + request (~.warehouse.CreateCollectionRequest): + The request object. Request message for CreateCollection. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/collections', + 'body': 'collection', + }, + ] + request, metadata = self._interceptor.pre_create_collection(request, metadata) + pb_request = warehouse.CreateCollectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_collection(resp) + return resp + + class _CreateCorpus(WarehouseRestStub): + def __hash__(self): + return hash("CreateCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create corpus method over HTTP. + + Args: + request (~.warehouse.CreateCorpusRequest): + The request object. Request message of CreateCorpus API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/corpora', + 'body': 'corpus', + }, + ] + request, metadata = self._interceptor.pre_create_corpus(request, metadata) + pb_request = warehouse.CreateCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_corpus(resp) + return resp + + class _CreateDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("CreateDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.DataSchema: + r"""Call the create data schema method over HTTP. + + Args: + request (~.warehouse.CreateDataSchemaRequest): + The request object. Request message for CreateDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/dataSchemas', + 'body': 'data_schema', + }, + ] + request, metadata = self._interceptor.pre_create_data_schema(request, metadata) + pb_request = warehouse.CreateDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.DataSchema() + pb_resp = warehouse.DataSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_data_schema(resp) + return resp + + class _CreateIndex(WarehouseRestStub): + def __hash__(self): + return hash("CreateIndex") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateIndexRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create index method over HTTP. + + Args: + request (~.warehouse.CreateIndexRequest): + The request object. Message for creating an Index. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/indexes', + 'body': 'index', + }, + ] + request, metadata = self._interceptor.pre_create_index(request, metadata) + pb_request = warehouse.CreateIndexRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_index(resp) + return resp + + class _CreateIndexEndpoint(WarehouseRestStub): + def __hash__(self): + return hash("CreateIndexEndpoint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateIndexEndpointRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create index endpoint method over HTTP. + + Args: + request (~.warehouse.CreateIndexEndpointRequest): + The request object. Request message for + CreateIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/indexEndpoints', + 'body': 'index_endpoint', + }, + ] + request, metadata = self._interceptor.pre_create_index_endpoint(request, metadata) + pb_request = warehouse.CreateIndexEndpointRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_index_endpoint(resp) + return resp + + class _CreateSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("CreateSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "searchConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchConfig: + r"""Call the create search config method over HTTP. + + Args: + request (~.warehouse.CreateSearchConfigRequest): + The request object. Request message for + CreateSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/searchConfigs', + 'body': 'search_config', + }, + ] + request, metadata = self._interceptor.pre_create_search_config(request, metadata) + pb_request = warehouse.CreateSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchConfig() + pb_resp = warehouse.SearchConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_search_config(resp) + return resp + + class _CreateSearchHypernym(WarehouseRestStub): + def __hash__(self): + return hash("CreateSearchHypernym") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateSearchHypernymRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchHypernym: + r"""Call the create search hypernym method over HTTP. + + Args: + request (~.warehouse.CreateSearchHypernymRequest): + The request object. Request message for creating + SearchHypernym. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchHypernym: + Search resource: SearchHypernym. For example, { + hypernym: "vehicle" hyponyms: ["sedan", "truck"] } This + means in SMART_SEARCH mode, searching for "vehicle" will + also return results with "sedan" or "truck" as + annotations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/searchHypernyms', + 'body': 'search_hypernym', + }, + ] + request, metadata = self._interceptor.pre_create_search_hypernym(request, metadata) + pb_request = warehouse.CreateSearchHypernymRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchHypernym() + pb_resp = warehouse.SearchHypernym.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_search_hypernym(resp) + return resp + + class _DeleteAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("DeleteAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete annotation method over HTTP. + + Args: + request (~.warehouse.DeleteAnnotationRequest): + The request object. Request message for DeleteAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_annotation(request, metadata) + pb_request = warehouse.DeleteAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteAsset(WarehouseRestStub): + def __hash__(self): + return hash("DeleteAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete asset method over HTTP. + + Args: + request (~.warehouse.DeleteAssetRequest): + The request object. Request message for DeleteAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_asset(request, metadata) + pb_request = warehouse.DeleteAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_asset(resp) + return resp + + class _DeleteCollection(WarehouseRestStub): + def __hash__(self): + return hash("DeleteCollection") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteCollectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete collection method over HTTP. + + Args: + request (~.warehouse.DeleteCollectionRequest): + The request object. Request message for + DeleteCollectionRequest. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_collection(request, metadata) + pb_request = warehouse.DeleteCollectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_collection(resp) + return resp + + class _DeleteCorpus(WarehouseRestStub): + def __hash__(self): + return hash("DeleteCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete corpus method over HTTP. + + Args: + request (~.warehouse.DeleteCorpusRequest): + The request object. Request message for DeleteCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_corpus(request, metadata) + pb_request = warehouse.DeleteCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("DeleteDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete data schema method over HTTP. + + Args: + request (~.warehouse.DeleteDataSchemaRequest): + The request object. Request message for DeleteDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_data_schema(request, metadata) + pb_request = warehouse.DeleteDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteIndex(WarehouseRestStub): + def __hash__(self): + return hash("DeleteIndex") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteIndexRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete index method over HTTP. + + Args: + request (~.warehouse.DeleteIndexRequest): + The request object. Request message for DeleteIndex. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_index(request, metadata) + pb_request = warehouse.DeleteIndexRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_index(resp) + return resp + + class _DeleteIndexEndpoint(WarehouseRestStub): + def __hash__(self): + return hash("DeleteIndexEndpoint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteIndexEndpointRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete index endpoint method over HTTP. + + Args: + request (~.warehouse.DeleteIndexEndpointRequest): + The request object. Request message for + DeleteIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_index_endpoint(request, metadata) + pb_request = warehouse.DeleteIndexEndpointRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_index_endpoint(resp) + return resp + + class _DeleteSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("DeleteSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete search config method over HTTP. + + Args: + request (~.warehouse.DeleteSearchConfigRequest): + The request object. Request message for + DeleteSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_search_config(request, metadata) + pb_request = warehouse.DeleteSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteSearchHypernym(WarehouseRestStub): + def __hash__(self): + return hash("DeleteSearchHypernym") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteSearchHypernymRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete search hypernym method over HTTP. + + Args: + request (~.warehouse.DeleteSearchHypernymRequest): + The request object. Request message for deleting + SearchHypernym. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/searchHypernyms/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_search_hypernym(request, metadata) + pb_request = warehouse.DeleteSearchHypernymRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeployIndex(WarehouseRestStub): + def __hash__(self): + return hash("DeployIndex") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeployIndexRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the deploy index method over HTTP. + + Args: + request (~.warehouse.DeployIndexRequest): + The request object. Request message for DeployIndex. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{index_endpoint=projects/*/locations/*/indexEndpoints/*}:deployIndex', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_deploy_index(request, metadata) + pb_request = warehouse.DeployIndexRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_deploy_index(resp) + return resp + + class _GenerateHlsUri(WarehouseRestStub): + def __hash__(self): + return hash("GenerateHlsUri") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GenerateHlsUriRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.GenerateHlsUriResponse: + r"""Call the generate hls uri method over HTTP. + + Args: + request (~.warehouse.GenerateHlsUriRequest): + The request object. Request message for GenerateHlsUri + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.GenerateHlsUriResponse: + Response message for GenerateHlsUri + API. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}:generateHlsUri', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_hls_uri(request, metadata) + pb_request = warehouse.GenerateHlsUriRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.GenerateHlsUriResponse() + pb_resp = warehouse.GenerateHlsUriResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_hls_uri(resp) + return resp + + class _GenerateRetrievalUrl(WarehouseRestStub): + def __hash__(self): + return hash("GenerateRetrievalUrl") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GenerateRetrievalUrlRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.GenerateRetrievalUrlResponse: + r"""Call the generate retrieval url method over HTTP. + + Args: + request (~.warehouse.GenerateRetrievalUrlRequest): + The request object. Request message for + GenerateRetrievalUrl API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.GenerateRetrievalUrlResponse: + Response message for + GenerateRetrievalUrl API. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}:generateRetrievalUrl', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_retrieval_url(request, metadata) + pb_request = warehouse.GenerateRetrievalUrlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.GenerateRetrievalUrlResponse() + pb_resp = warehouse.GenerateRetrievalUrlResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_retrieval_url(resp) + return resp + + class _GetAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("GetAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Annotation: + r"""Call the get annotation method over HTTP. + + Args: + request (~.warehouse.GetAnnotationRequest): + The request object. Request message for GetAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_annotation(request, metadata) + pb_request = warehouse.GetAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Annotation() + pb_resp = warehouse.Annotation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_annotation(resp) + return resp + + class _GetAsset(WarehouseRestStub): + def __hash__(self): + return hash("GetAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Asset: + r"""Call the get asset method over HTTP. + + Args: + request (~.warehouse.GetAssetRequest): + The request object. Request message for GetAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}', + }, + ] + request, metadata = self._interceptor.pre_get_asset(request, metadata) + pb_request = warehouse.GetAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Asset() + pb_resp = warehouse.Asset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_asset(resp) + return resp + + class _GetCollection(WarehouseRestStub): + def __hash__(self): + return hash("GetCollection") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetCollectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Collection: + r"""Call the get collection method over HTTP. + + Args: + request (~.warehouse.GetCollectionRequest): + The request object. Request message for + GetCollectionRequest. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Collection: + A collection is a resource in a + corpus. It serves as a container of + references to original resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*}', + }, + ] + request, metadata = self._interceptor.pre_get_collection(request, metadata) + pb_request = warehouse.GetCollectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Collection() + pb_resp = warehouse.Collection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_collection(resp) + return resp + + class _GetCorpus(WarehouseRestStub): + def __hash__(self): + return hash("GetCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Corpus: + r"""Call the get corpus method over HTTP. + + Args: + request (~.warehouse.GetCorpusRequest): + The request object. Request message for GetCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Corpus: + Corpus is a set of media contents for + management. Within a corpus, media + shares the same data schema. Search is + also restricted within a single corpus. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*}', + }, + ] + request, metadata = self._interceptor.pre_get_corpus(request, metadata) + pb_request = warehouse.GetCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Corpus() + pb_resp = warehouse.Corpus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_corpus(resp) + return resp + + class _GetDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("GetDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.DataSchema: + r"""Call the get data schema method over HTTP. + + Args: + request (~.warehouse.GetDataSchemaRequest): + The request object. Request message for GetDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}', + }, + ] + request, metadata = self._interceptor.pre_get_data_schema(request, metadata) + pb_request = warehouse.GetDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.DataSchema() + pb_resp = warehouse.DataSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_schema(resp) + return resp + + class _GetIndex(WarehouseRestStub): + def __hash__(self): + return hash("GetIndex") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetIndexRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Index: + r"""Call the get index method over HTTP. + + Args: + request (~.warehouse.GetIndexRequest): + The request object. Request message for getting an Index. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Index: + An Index is a resource in Corpus. It + contains an indexed version of the + assets and annotations. When deployed to + an endpoint, it will allow users to + search the Index. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*}', + }, + ] + request, metadata = self._interceptor.pre_get_index(request, metadata) + pb_request = warehouse.GetIndexRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Index() + pb_resp = warehouse.Index.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_index(resp) + return resp + + class _GetIndexEndpoint(WarehouseRestStub): + def __hash__(self): + return hash("GetIndexEndpoint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetIndexEndpointRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.IndexEndpoint: + r"""Call the get index endpoint method over HTTP. + + Args: + request (~.warehouse.GetIndexEndpointRequest): + The request object. Request message for GetIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.IndexEndpoint: + Message representing IndexEndpoint + resource. Indexes are deployed into it. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*}', + }, + ] + request, metadata = self._interceptor.pre_get_index_endpoint(request, metadata) + pb_request = warehouse.GetIndexEndpointRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.IndexEndpoint() + pb_resp = warehouse.IndexEndpoint.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_index_endpoint(resp) + return resp + + class _GetSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("GetSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchConfig: + r"""Call the get search config method over HTTP. + + Args: + request (~.warehouse.GetSearchConfigRequest): + The request object. Request message for GetSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_search_config(request, metadata) + pb_request = warehouse.GetSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchConfig() + pb_resp = warehouse.SearchConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_search_config(resp) + return resp + + class _GetSearchHypernym(WarehouseRestStub): + def __hash__(self): + return hash("GetSearchHypernym") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetSearchHypernymRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchHypernym: + r"""Call the get search hypernym method over HTTP. + + Args: + request (~.warehouse.GetSearchHypernymRequest): + The request object. Request message for getting + SearchHypernym. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchHypernym: + Search resource: SearchHypernym. For example, { + hypernym: "vehicle" hyponyms: ["sedan", "truck"] } This + means in SMART_SEARCH mode, searching for "vehicle" will + also return results with "sedan" or "truck" as + annotations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/searchHypernyms/*}', + }, + ] + request, metadata = self._interceptor.pre_get_search_hypernym(request, metadata) + pb_request = warehouse.GetSearchHypernymRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchHypernym() + pb_resp = warehouse.SearchHypernym.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_search_hypernym(resp) + return resp + + class _ImportAssets(WarehouseRestStub): + def __hash__(self): + return hash("ImportAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ImportAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import assets method over HTTP. + + Args: + request (~.warehouse.ImportAssetsRequest): + The request object. The request message for ImportAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/assets:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_assets(request, metadata) + pb_request = warehouse.ImportAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_assets(resp) + return resp + + class _IndexAsset(WarehouseRestStub): + def __hash__(self): + return hash("IndexAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.IndexAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the index asset method over HTTP. + + Args: + request (~.warehouse.IndexAssetRequest): + The request object. Request message for IndexAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}:index', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_index_asset(request, metadata) + pb_request = warehouse.IndexAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_index_asset(resp) + return resp + + class _IngestAsset(WarehouseRestStub): + def __hash__(self): + return hash("IngestAsset") + + def __call__(self, + request: warehouse.IngestAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method IngestAsset is not available over REST transport" + ) + class _ListAnnotations(WarehouseRestStub): + def __hash__(self): + return hash("ListAnnotations") + + def __call__(self, + request: warehouse.ListAnnotationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListAnnotationsResponse: + r"""Call the list annotations method over HTTP. + + Args: + request (~.warehouse.ListAnnotationsRequest): + The request object. Request message for GetAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListAnnotationsResponse: + Request message for ListAnnotations + API. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations', + }, + ] + request, metadata = self._interceptor.pre_list_annotations(request, metadata) + pb_request = warehouse.ListAnnotationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListAnnotationsResponse() + pb_resp = warehouse.ListAnnotationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_annotations(resp) + return resp + + class _ListAssets(WarehouseRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.warehouse.ListAssetsRequest): + The request object. Request message for ListAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListAssetsResponse: + Response message for ListAssets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = warehouse.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListAssetsResponse() + pb_resp = warehouse.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListCollections(WarehouseRestStub): + def __hash__(self): + return hash("ListCollections") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListCollectionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListCollectionsResponse: + r"""Call the list collections method over HTTP. + + Args: + request (~.warehouse.ListCollectionsRequest): + The request object. Request message for ListCollections. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListCollectionsResponse: + Response message for ListCollections. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/collections', + }, + ] + request, metadata = self._interceptor.pre_list_collections(request, metadata) + pb_request = warehouse.ListCollectionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListCollectionsResponse() + pb_resp = warehouse.ListCollectionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_collections(resp) + return resp + + class _ListCorpora(WarehouseRestStub): + def __hash__(self): + return hash("ListCorpora") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListCorporaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListCorporaResponse: + r"""Call the list corpora method over HTTP. + + Args: + request (~.warehouse.ListCorporaRequest): + The request object. Request message for ListCorpora. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListCorporaResponse: + Response message for ListCorpora. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/corpora', + }, + ] + request, metadata = self._interceptor.pre_list_corpora(request, metadata) + pb_request = warehouse.ListCorporaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListCorporaResponse() + pb_resp = warehouse.ListCorporaResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_corpora(resp) + return resp + + class _ListDataSchemas(WarehouseRestStub): + def __hash__(self): + return hash("ListDataSchemas") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListDataSchemasRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListDataSchemasResponse: + r"""Call the list data schemas method over HTTP. + + Args: + request (~.warehouse.ListDataSchemasRequest): + The request object. Request message for ListDataSchemas. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListDataSchemasResponse: + Response message for ListDataSchemas. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/dataSchemas', + }, + ] + request, metadata = self._interceptor.pre_list_data_schemas(request, metadata) + pb_request = warehouse.ListDataSchemasRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListDataSchemasResponse() + pb_resp = warehouse.ListDataSchemasResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_data_schemas(resp) + return resp + + class _ListIndexEndpoints(WarehouseRestStub): + def __hash__(self): + return hash("ListIndexEndpoints") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListIndexEndpointsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListIndexEndpointsResponse: + r"""Call the list index endpoints method over HTTP. + + Args: + request (~.warehouse.ListIndexEndpointsRequest): + The request object. Request message for + ListIndexEndpoints. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListIndexEndpointsResponse: + Response message for + ListIndexEndpoints. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/indexEndpoints', + }, + ] + request, metadata = self._interceptor.pre_list_index_endpoints(request, metadata) + pb_request = warehouse.ListIndexEndpointsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListIndexEndpointsResponse() + pb_resp = warehouse.ListIndexEndpointsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_index_endpoints(resp) + return resp + + class _ListIndexes(WarehouseRestStub): + def __hash__(self): + return hash("ListIndexes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListIndexesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListIndexesResponse: + r"""Call the list indexes method over HTTP. + + Args: + request (~.warehouse.ListIndexesRequest): + The request object. Request message for listing Indexes. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListIndexesResponse: + Response message for ListIndexes. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/indexes', + }, + ] + request, metadata = self._interceptor.pre_list_indexes(request, metadata) + pb_request = warehouse.ListIndexesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListIndexesResponse() + pb_resp = warehouse.ListIndexesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_indexes(resp) + return resp + + class _ListSearchConfigs(WarehouseRestStub): + def __hash__(self): + return hash("ListSearchConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListSearchConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListSearchConfigsResponse: + r"""Call the list search configs method over HTTP. + + Args: + request (~.warehouse.ListSearchConfigsRequest): + The request object. Request message for + ListSearchConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListSearchConfigsResponse: + Response message for + ListSearchConfigs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/searchConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_search_configs(request, metadata) + pb_request = warehouse.ListSearchConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListSearchConfigsResponse() + pb_resp = warehouse.ListSearchConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_search_configs(resp) + return resp + + class _ListSearchHypernyms(WarehouseRestStub): + def __hash__(self): + return hash("ListSearchHypernyms") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListSearchHypernymsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListSearchHypernymsResponse: + r"""Call the list search hypernyms method over HTTP. + + Args: + request (~.warehouse.ListSearchHypernymsRequest): + The request object. Request message for listing + SearchHypernyms. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListSearchHypernymsResponse: + Response message for listing + SearchHypernyms. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/corpora/*}/searchHypernyms', + }, + ] + request, metadata = self._interceptor.pre_list_search_hypernyms(request, metadata) + pb_request = warehouse.ListSearchHypernymsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListSearchHypernymsResponse() + pb_resp = warehouse.ListSearchHypernymsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_search_hypernyms(resp) + return resp + + class _RemoveCollectionItem(WarehouseRestStub): + def __hash__(self): + return hash("RemoveCollectionItem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.RemoveCollectionItemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.RemoveCollectionItemResponse: + r"""Call the remove collection item method over HTTP. + + Args: + request (~.warehouse.RemoveCollectionItemRequest): + The request object. Request message for + RemoveCollectionItem. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.RemoveCollectionItemResponse: + Request message for + RemoveCollectionItem. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{item.collection=projects/*/locations/*/corpora/*/collections/*}:removeCollectionItem', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_remove_collection_item(request, metadata) + pb_request = warehouse.RemoveCollectionItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.RemoveCollectionItemResponse() + pb_resp = warehouse.RemoveCollectionItemResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_remove_collection_item(resp) + return resp + + class _RemoveIndexAsset(WarehouseRestStub): + def __hash__(self): + return hash("RemoveIndexAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.RemoveIndexAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the remove index asset method over HTTP. + + Args: + request (~.warehouse.RemoveIndexAssetRequest): + The request object. Request message for RemoveIndexAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}:removeIndex', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_remove_index_asset(request, metadata) + pb_request = warehouse.RemoveIndexAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_remove_index_asset(resp) + return resp + + class _SearchAssets(WarehouseRestStub): + def __hash__(self): + return hash("SearchAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.SearchAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchAssetsResponse: + r"""Call the search assets method over HTTP. + + Args: + request (~.warehouse.SearchAssetsRequest): + The request object. Request message for SearchAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchAssetsResponse: + Response message for SearchAssets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{corpus=projects/*/locations/*/corpora/*}:searchAssets', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search_assets(request, metadata) + pb_request = warehouse.SearchAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchAssetsResponse() + pb_resp = warehouse.SearchAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_assets(resp) + return resp + + class _SearchIndexEndpoint(WarehouseRestStub): + def __hash__(self): + return hash("SearchIndexEndpoint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.SearchIndexEndpointRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchIndexEndpointResponse: + r"""Call the search index endpoint method over HTTP. + + Args: + request (~.warehouse.SearchIndexEndpointRequest): + The request object. Request message for + SearchIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchIndexEndpointResponse: + Response message for + SearchIndexEndpoint. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{index_endpoint=projects/*/locations/*/indexEndpoints/*}:searchIndexEndpoint', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search_index_endpoint(request, metadata) + pb_request = warehouse.SearchIndexEndpointRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchIndexEndpointResponse() + pb_resp = warehouse.SearchIndexEndpointResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_index_endpoint(resp) + return resp + + class _UndeployIndex(WarehouseRestStub): + def __hash__(self): + return hash("UndeployIndex") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UndeployIndexRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the undeploy index method over HTTP. + + Args: + request (~.warehouse.UndeployIndexRequest): + The request object. Request message for + UndeployIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{index_endpoint=projects/*/locations/*/indexEndpoints/*}:undeployIndex', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_undeploy_index(request, metadata) + pb_request = warehouse.UndeployIndexRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undeploy_index(resp) + return resp + + class _UpdateAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("UpdateAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Annotation: + r"""Call the update annotation method over HTTP. + + Args: + request (~.warehouse.UpdateAnnotationRequest): + The request object. Request message for UpdateAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{annotation.name=projects/*/locations/*/corpora/*/assets/*/annotations/*}', + 'body': 'annotation', + }, + ] + request, metadata = self._interceptor.pre_update_annotation(request, metadata) + pb_request = warehouse.UpdateAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Annotation() + pb_resp = warehouse.Annotation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_annotation(resp) + return resp + + class _UpdateAsset(WarehouseRestStub): + def __hash__(self): + return hash("UpdateAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Asset: + r"""Call the update asset method over HTTP. + + Args: + request (~.warehouse.UpdateAssetRequest): + The request object. Request message for UpdateAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{asset.name=projects/*/locations/*/corpora/*/assets/*}', + 'body': 'asset', + }, + ] + request, metadata = self._interceptor.pre_update_asset(request, metadata) + pb_request = warehouse.UpdateAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Asset() + pb_resp = warehouse.Asset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_asset(resp) + return resp + + class _UpdateCollection(WarehouseRestStub): + def __hash__(self): + return hash("UpdateCollection") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateCollectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Collection: + r"""Call the update collection method over HTTP. + + Args: + request (~.warehouse.UpdateCollectionRequest): + The request object. Request message for + UpdateCollectionRequest. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Collection: + A collection is a resource in a + corpus. It serves as a container of + references to original resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{collection.name=projects/*/locations/*/corpora/*/collections/*}', + 'body': 'collection', + }, + ] + request, metadata = self._interceptor.pre_update_collection(request, metadata) + pb_request = warehouse.UpdateCollectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Collection() + pb_resp = warehouse.Collection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_collection(resp) + return resp + + class _UpdateCorpus(WarehouseRestStub): + def __hash__(self): + return hash("UpdateCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Corpus: + r"""Call the update corpus method over HTTP. + + Args: + request (~.warehouse.UpdateCorpusRequest): + The request object. Request message for UpdateCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Corpus: + Corpus is a set of media contents for + management. Within a corpus, media + shares the same data schema. Search is + also restricted within a single corpus. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{corpus.name=projects/*/locations/*/corpora/*}', + 'body': 'corpus', + }, + ] + request, metadata = self._interceptor.pre_update_corpus(request, metadata) + pb_request = warehouse.UpdateCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Corpus() + pb_resp = warehouse.Corpus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_corpus(resp) + return resp + + class _UpdateDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("UpdateDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.DataSchema: + r"""Call the update data schema method over HTTP. + + Args: + request (~.warehouse.UpdateDataSchemaRequest): + The request object. Request message for UpdateDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{data_schema.name=projects/*/locations/*/corpora/*/dataSchemas/*}', + 'body': 'data_schema', + }, + ] + request, metadata = self._interceptor.pre_update_data_schema(request, metadata) + pb_request = warehouse.UpdateDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.DataSchema() + pb_resp = warehouse.DataSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_schema(resp) + return resp + + class _UpdateIndex(WarehouseRestStub): + def __hash__(self): + return hash("UpdateIndex") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateIndexRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update index method over HTTP. + + Args: + request (~.warehouse.UpdateIndexRequest): + The request object. Request message for UpdateIndex. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{index.name=projects/*/locations/*/corpora/*/indexes/*}', + 'body': 'index', + }, + ] + request, metadata = self._interceptor.pre_update_index(request, metadata) + pb_request = warehouse.UpdateIndexRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_index(resp) + return resp + + class _UpdateIndexEndpoint(WarehouseRestStub): + def __hash__(self): + return hash("UpdateIndexEndpoint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateIndexEndpointRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update index endpoint method over HTTP. + + Args: + request (~.warehouse.UpdateIndexEndpointRequest): + The request object. Request message for + UpdateIndexEndpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{index_endpoint.name=projects/*/locations/*/indexEndpoints/*}', + 'body': 'index_endpoint', + }, + ] + request, metadata = self._interceptor.pre_update_index_endpoint(request, metadata) + pb_request = warehouse.UpdateIndexEndpointRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_index_endpoint(resp) + return resp + + class _UpdateSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("UpdateSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchConfig: + r"""Call the update search config method over HTTP. + + Args: + request (~.warehouse.UpdateSearchConfigRequest): + The request object. Request message for + UpdateSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{search_config.name=projects/*/locations/*/corpora/*/searchConfigs/*}', + 'body': 'search_config', + }, + ] + request, metadata = self._interceptor.pre_update_search_config(request, metadata) + pb_request = warehouse.UpdateSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchConfig() + pb_resp = warehouse.SearchConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_search_config(resp) + return resp + + class _UpdateSearchHypernym(WarehouseRestStub): + def __hash__(self): + return hash("UpdateSearchHypernym") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateSearchHypernymRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchHypernym: + r"""Call the update search hypernym method over HTTP. + + Args: + request (~.warehouse.UpdateSearchHypernymRequest): + The request object. Request message for updating + SearchHypernym. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchHypernym: + Search resource: SearchHypernym. For example, { + hypernym: "vehicle" hyponyms: ["sedan", "truck"] } This + means in SMART_SEARCH mode, searching for "vehicle" will + also return results with "sedan" or "truck" as + annotations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{search_hypernym.name=projects/*/locations/*/corpora/*/searchHypernyms/*}', + 'body': 'search_hypernym', + }, + ] + request, metadata = self._interceptor.pre_update_search_hypernym(request, metadata) + pb_request = warehouse.UpdateSearchHypernymRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchHypernym() + pb_resp = warehouse.SearchHypernym.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_search_hypernym(resp) + return resp + + class _UploadAsset(WarehouseRestStub): + def __hash__(self): + return hash("UploadAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UploadAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the upload asset method over HTTP. + + Args: + request (~.warehouse.UploadAssetRequest): + The request object. Request message for UploadAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*}:upload', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_upload_asset(request, metadata) + pb_request = warehouse.UploadAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_upload_asset(resp) + return resp + + class _ViewCollectionItems(WarehouseRestStub): + def __hash__(self): + return hash("ViewCollectionItems") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ViewCollectionItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ViewCollectionItemsResponse: + r"""Call the view collection items method over HTTP. + + Args: + request (~.warehouse.ViewCollectionItemsRequest): + The request object. Request message for + ViewCollectionItems. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ViewCollectionItemsResponse: + Response message for + ViewCollectionItems. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{collection=projects/*/locations/*/corpora/*/collections/*}:viewCollectionItems', + }, + ] + request, metadata = self._interceptor.pre_view_collection_items(request, metadata) + pb_request = warehouse.ViewCollectionItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ViewCollectionItemsResponse() + pb_resp = warehouse.ViewCollectionItemsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_view_collection_items(resp) + return resp + + class _ViewIndexedAssets(WarehouseRestStub): + def __hash__(self): + return hash("ViewIndexedAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ViewIndexedAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ViewIndexedAssetsResponse: + r"""Call the view indexed assets method over HTTP. + + Args: + request (~.warehouse.ViewIndexedAssetsRequest): + The request object. Request message for + ViewIndexedAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ViewIndexedAssetsResponse: + Response message for + ViewIndexedAssets. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{index=projects/*/locations/*/corpora/*/indexes/*}:viewAssets', + }, + ] + request, metadata = self._interceptor.pre_view_indexed_assets(request, metadata) + pb_request = warehouse.ViewIndexedAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ViewIndexedAssetsResponse() + pb_resp = warehouse.ViewIndexedAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_view_indexed_assets(resp) + return resp + + @property + def add_collection_item(self) -> Callable[ + [warehouse.AddCollectionItemRequest], + warehouse.AddCollectionItemResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AddCollectionItem(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_asset(self) -> Callable[ + [warehouse.AnalyzeAssetRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_corpus(self) -> Callable[ + [warehouse.AnalyzeCorpusRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + warehouse.ClipAssetResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ClipAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + warehouse.Annotation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + warehouse.Asset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_collection(self) -> Callable[ + [warehouse.CreateCollectionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCollection(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + warehouse.DataSchema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_index(self) -> Callable[ + [warehouse.CreateIndexRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateIndex(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_index_endpoint(self) -> Callable[ + [warehouse.CreateIndexEndpointRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateIndexEndpoint(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + warehouse.SearchConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_search_hypernym(self) -> Callable[ + [warehouse.CreateSearchHypernymRequest], + warehouse.SearchHypernym]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSearchHypernym(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_collection(self) -> Callable[ + [warehouse.DeleteCollectionRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCollection(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_index(self) -> Callable[ + [warehouse.DeleteIndexRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteIndex(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_index_endpoint(self) -> Callable[ + [warehouse.DeleteIndexEndpointRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteIndexEndpoint(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_search_hypernym(self) -> Callable[ + [warehouse.DeleteSearchHypernymRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSearchHypernym(self._session, self._host, self._interceptor) # type: ignore + + @property + def deploy_index(self) -> Callable[ + [warehouse.DeployIndexRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeployIndex(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + warehouse.GenerateHlsUriResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateHlsUri(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_retrieval_url(self) -> Callable[ + [warehouse.GenerateRetrievalUrlRequest], + warehouse.GenerateRetrievalUrlResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateRetrievalUrl(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + warehouse.Annotation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + warehouse.Asset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_collection(self) -> Callable[ + [warehouse.GetCollectionRequest], + warehouse.Collection]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCollection(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + warehouse.Corpus]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + warehouse.DataSchema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_index(self) -> Callable[ + [warehouse.GetIndexRequest], + warehouse.Index]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIndex(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_index_endpoint(self) -> Callable[ + [warehouse.GetIndexEndpointRequest], + warehouse.IndexEndpoint]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIndexEndpoint(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + warehouse.SearchConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_search_hypernym(self) -> Callable[ + [warehouse.GetSearchHypernymRequest], + warehouse.SearchHypernym]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSearchHypernym(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_assets(self) -> Callable[ + [warehouse.ImportAssetsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def index_asset(self) -> Callable[ + [warehouse.IndexAssetRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._IndexAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + warehouse.IngestAssetResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._IngestAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + warehouse.ListAnnotationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAnnotations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + warehouse.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_collections(self) -> Callable[ + [warehouse.ListCollectionsRequest], + warehouse.ListCollectionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCollections(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + warehouse.ListCorporaResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCorpora(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + warehouse.ListDataSchemasResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDataSchemas(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_index_endpoints(self) -> Callable[ + [warehouse.ListIndexEndpointsRequest], + warehouse.ListIndexEndpointsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListIndexEndpoints(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_indexes(self) -> Callable[ + [warehouse.ListIndexesRequest], + warehouse.ListIndexesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListIndexes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + warehouse.ListSearchConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSearchConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_search_hypernyms(self) -> Callable[ + [warehouse.ListSearchHypernymsRequest], + warehouse.ListSearchHypernymsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSearchHypernyms(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_collection_item(self) -> Callable[ + [warehouse.RemoveCollectionItemRequest], + warehouse.RemoveCollectionItemResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveCollectionItem(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_index_asset(self) -> Callable[ + [warehouse.RemoveIndexAssetRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveIndexAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + warehouse.SearchAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_index_endpoint(self) -> Callable[ + [warehouse.SearchIndexEndpointRequest], + warehouse.SearchIndexEndpointResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchIndexEndpoint(self._session, self._host, self._interceptor) # type: ignore + + @property + def undeploy_index(self) -> Callable[ + [warehouse.UndeployIndexRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeployIndex(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + warehouse.Annotation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + warehouse.Asset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_collection(self) -> Callable[ + [warehouse.UpdateCollectionRequest], + warehouse.Collection]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCollection(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + warehouse.Corpus]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + warehouse.DataSchema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_index(self) -> Callable[ + [warehouse.UpdateIndexRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateIndex(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_index_endpoint(self) -> Callable[ + [warehouse.UpdateIndexEndpointRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateIndexEndpoint(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + warehouse.SearchConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_search_hypernym(self) -> Callable[ + [warehouse.UpdateSearchHypernymRequest], + warehouse.SearchHypernym]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSearchHypernym(self._session, self._host, self._interceptor) # type: ignore + + @property + def upload_asset(self) -> Callable[ + [warehouse.UploadAssetRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UploadAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def view_collection_items(self) -> Callable[ + [warehouse.ViewCollectionItemsRequest], + warehouse.ViewCollectionItemsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ViewCollectionItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def view_indexed_assets(self) -> Callable[ + [warehouse.ViewIndexedAssetsRequest], + warehouse.ViewIndexedAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ViewIndexedAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(WarehouseRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(WarehouseRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(WarehouseRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/imageIndexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/indexes/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/corpora/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/indexEndpoints/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(WarehouseRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WarehouseRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/__init__.py new file mode 100644 index 000000000000..c6b34223da14 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/__init__.py @@ -0,0 +1,740 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .annotations import ( + AppPlatformCloudFunctionRequest, + AppPlatformCloudFunctionResponse, + AppPlatformEventBody, + AppPlatformMetadata, + ClassificationPredictionResult, + ImageObjectDetectionPredictionResult, + ImageSegmentationPredictionResult, + NormalizedPolygon, + NormalizedPolyline, + NormalizedVertex, + ObjectDetectionPredictionResult, + OccupancyCountingPredictionResult, + PersonalProtectiveEquipmentDetectionOutput, + StreamAnnotation, + StreamAnnotations, + VideoActionRecognitionPredictionResult, + VideoClassificationPredictionResult, + VideoObjectTrackingPredictionResult, + StreamAnnotationType, +) +from .common import ( + Cluster, + GcsSource, + OperationMetadata, +) +from .health_service import ( + ClusterInfo, + HealthCheckRequest, + HealthCheckResponse, +) +from .lva import ( + AnalysisDefinition, + AnalyzerDefinition, + AttributeValue, + OperatorDefinition, + ResourceSpecification, + RunStatus, + RunMode, +) +from .lva_resources import ( + Analysis, + Operator, + Process, +) +from .lva_service import ( + BatchRunProcessRequest, + BatchRunProcessResponse, + CreateAnalysisRequest, + CreateOperatorRequest, + CreateProcessRequest, + DeleteAnalysisRequest, + DeleteOperatorRequest, + DeleteProcessRequest, + GetAnalysisRequest, + GetOperatorRequest, + GetProcessRequest, + ListAnalysesRequest, + ListAnalysesResponse, + ListOperatorsRequest, + ListOperatorsResponse, + ListProcessesRequest, + ListProcessesResponse, + ListPublicOperatorsRequest, + ListPublicOperatorsResponse, + OperatorQuery, + ResolveOperatorInfoRequest, + ResolveOperatorInfoResponse, + UpdateAnalysisRequest, + UpdateOperatorRequest, + UpdateProcessRequest, + Registry, +) +from .platform import ( + AddApplicationStreamInputRequest, + AddApplicationStreamInputResponse, + AIEnabledDevicesInputConfig, + Application, + ApplicationConfigs, + ApplicationInstance, + ApplicationNodeAnnotation, + ApplicationStreamInput, + AutoscalingMetricSpec, + BigQueryConfig, + CreateApplicationInstancesRequest, + CreateApplicationInstancesResponse, + CreateApplicationRequest, + CreateDraftRequest, + CreateProcessorRequest, + CustomProcessorSourceInfo, + DedicatedResources, + DeleteApplicationInstancesRequest, + DeleteApplicationInstancesResponse, + DeleteApplicationRequest, + DeleteDraftRequest, + DeleteProcessorRequest, + DeployApplicationRequest, + DeployApplicationResponse, + Draft, + GcsOutputConfig, + GeneralObjectDetectionConfig, + GetApplicationRequest, + GetDraftRequest, + GetInstanceRequest, + GetProcessorRequest, + Instance, + ListApplicationsRequest, + ListApplicationsResponse, + ListDraftsRequest, + ListDraftsResponse, + ListInstancesRequest, + ListInstancesResponse, + ListPrebuiltProcessorsRequest, + ListPrebuiltProcessorsResponse, + ListProcessorsRequest, + ListProcessorsResponse, + MachineSpec, + MediaWarehouseConfig, + Node, + OccupancyCountConfig, + PersonalProtectiveEquipmentDetectionConfig, + PersonBlurConfig, + PersonVehicleDetectionConfig, + Processor, + ProcessorConfig, + ProcessorIOSpec, + ProductRecognizerConfig, + RemoveApplicationStreamInputRequest, + RemoveApplicationStreamInputResponse, + ResourceAnnotations, + StreamWithAnnotation, + TagParsingConfig, + TagRecognizerConfig, + UndeployApplicationRequest, + UndeployApplicationResponse, + UniversalInputConfig, + UpdateApplicationInstancesRequest, + UpdateApplicationInstancesResponse, + UpdateApplicationRequest, + UpdateApplicationStreamInputRequest, + UpdateApplicationStreamInputResponse, + UpdateDraftRequest, + UpdateProcessorRequest, + VertexAutoMLVideoConfig, + VertexAutoMLVisionConfig, + VertexCustomConfig, + VideoStreamInputConfig, + AcceleratorType, + DataType, + ModelType, +) +from .streaming_resources import ( + GstreamerBufferDescriptor, + Packet, + PacketHeader, + PacketType, + RawImageDescriptor, + SeriesMetadata, + ServerMetadata, +) +from .streaming_service import ( + AcquireLeaseRequest, + CommitRequest, + ControlledMode, + EagerMode, + EventUpdate, + Lease, + ReceiveEventsControlResponse, + ReceiveEventsRequest, + ReceiveEventsResponse, + ReceivePacketsControlResponse, + ReceivePacketsRequest, + ReceivePacketsResponse, + ReleaseLeaseRequest, + ReleaseLeaseResponse, + RenewLeaseRequest, + RequestMetadata, + SendPacketsRequest, + SendPacketsResponse, + LeaseType, +) +from .streams_resources import ( + Channel, + Event, + Series, + Stream, +) +from .streams_service import ( + CreateClusterRequest, + CreateEventRequest, + CreateSeriesRequest, + CreateStreamRequest, + DeleteClusterRequest, + DeleteEventRequest, + DeleteSeriesRequest, + DeleteStreamRequest, + GenerateStreamHlsTokenRequest, + GenerateStreamHlsTokenResponse, + GetClusterRequest, + GetEventRequest, + GetSeriesRequest, + GetStreamRequest, + GetStreamThumbnailRequest, + GetStreamThumbnailResponse, + ListClustersRequest, + ListClustersResponse, + ListEventsRequest, + ListEventsResponse, + ListSeriesRequest, + ListSeriesResponse, + ListStreamsRequest, + ListStreamsResponse, + MaterializeChannelRequest, + UpdateClusterRequest, + UpdateEventRequest, + UpdateSeriesRequest, + UpdateStreamRequest, +) +from .warehouse import ( + AddCollectionItemRequest, + AddCollectionItemResponse, + AnalyzeAssetMetadata, + AnalyzeAssetRequest, + AnalyzeAssetResponse, + AnalyzeCorpusMetadata, + AnalyzeCorpusRequest, + AnalyzeCorpusResponse, + Annotation, + AnnotationCustomizedStruct, + AnnotationList, + AnnotationMatchingResult, + AnnotationValue, + Asset, + AssetSource, + BoolValue, + CircleArea, + ClipAssetRequest, + ClipAssetResponse, + Collection, + CollectionItem, + Corpus, + CreateAnnotationRequest, + CreateAssetRequest, + CreateCollectionMetadata, + CreateCollectionRequest, + CreateCorpusMetadata, + CreateCorpusRequest, + CreateDataSchemaRequest, + CreateIndexEndpointMetadata, + CreateIndexEndpointRequest, + CreateIndexMetadata, + CreateIndexRequest, + CreateSearchConfigRequest, + CreateSearchHypernymRequest, + Criteria, + DataSchema, + DataSchemaDetails, + DateTimeRange, + DateTimeRangeArray, + DeleteAnnotationRequest, + DeleteAssetMetadata, + DeleteAssetRequest, + DeleteCollectionMetadata, + DeleteCollectionRequest, + DeleteCorpusRequest, + DeleteDataSchemaRequest, + DeleteIndexEndpointMetadata, + DeleteIndexEndpointRequest, + DeleteIndexMetadata, + DeleteIndexRequest, + DeleteSearchConfigRequest, + DeleteSearchHypernymRequest, + DeployedIndex, + DeployedIndexReference, + DeployIndexMetadata, + DeployIndexRequest, + DeployIndexResponse, + FacetBucket, + FacetGroup, + FacetProperty, + FacetValue, + FloatRange, + FloatRangeArray, + GenerateHlsUriRequest, + GenerateHlsUriResponse, + GenerateRetrievalUrlRequest, + GenerateRetrievalUrlResponse, + GeoCoordinate, + GeoLocationArray, + GetAnnotationRequest, + GetAssetRequest, + GetCollectionRequest, + GetCorpusRequest, + GetDataSchemaRequest, + GetIndexEndpointRequest, + GetIndexRequest, + GetSearchConfigRequest, + GetSearchHypernymRequest, + ImageQuery, + ImportAssetsMetadata, + ImportAssetsRequest, + ImportAssetsResponse, + Index, + IndexAssetMetadata, + IndexAssetRequest, + IndexAssetResponse, + IndexedAsset, + IndexEndpoint, + IndexingStatus, + IngestAssetRequest, + IngestAssetResponse, + IntRange, + IntRangeArray, + ListAnnotationsRequest, + ListAnnotationsResponse, + ListAssetsRequest, + ListAssetsResponse, + ListCollectionsRequest, + ListCollectionsResponse, + ListCorporaRequest, + ListCorporaResponse, + ListDataSchemasRequest, + ListDataSchemasResponse, + ListIndexEndpointsRequest, + ListIndexEndpointsResponse, + ListIndexesRequest, + ListIndexesResponse, + ListSearchConfigsRequest, + ListSearchConfigsResponse, + ListSearchHypernymsRequest, + ListSearchHypernymsResponse, + Partition, + RemoveCollectionItemRequest, + RemoveCollectionItemResponse, + RemoveIndexAssetMetadata, + RemoveIndexAssetRequest, + RemoveIndexAssetResponse, + SchemaKeySortingStrategy, + SearchAssetsRequest, + SearchAssetsResponse, + SearchCapability, + SearchCapabilitySetting, + SearchConfig, + SearchCriteriaProperty, + SearchHypernym, + SearchIndexEndpointRequest, + SearchIndexEndpointResponse, + SearchResultItem, + StringArray, + UndeployIndexMetadata, + UndeployIndexRequest, + UndeployIndexResponse, + UpdateAnnotationRequest, + UpdateAssetRequest, + UpdateCollectionRequest, + UpdateCorpusRequest, + UpdateDataSchemaRequest, + UpdateIndexEndpointMetadata, + UpdateIndexEndpointRequest, + UpdateIndexMetadata, + UpdateIndexRequest, + UpdateSearchConfigRequest, + UpdateSearchHypernymRequest, + UploadAssetMetadata, + UploadAssetRequest, + UploadAssetResponse, + UserSpecifiedAnnotation, + ViewCollectionItemsRequest, + ViewCollectionItemsResponse, + ViewIndexedAssetsRequest, + ViewIndexedAssetsResponse, + FacetBucketType, +) + +__all__ = ( + 'AppPlatformCloudFunctionRequest', + 'AppPlatformCloudFunctionResponse', + 'AppPlatformEventBody', + 'AppPlatformMetadata', + 'ClassificationPredictionResult', + 'ImageObjectDetectionPredictionResult', + 'ImageSegmentationPredictionResult', + 'NormalizedPolygon', + 'NormalizedPolyline', + 'NormalizedVertex', + 'ObjectDetectionPredictionResult', + 'OccupancyCountingPredictionResult', + 'PersonalProtectiveEquipmentDetectionOutput', + 'StreamAnnotation', + 'StreamAnnotations', + 'VideoActionRecognitionPredictionResult', + 'VideoClassificationPredictionResult', + 'VideoObjectTrackingPredictionResult', + 'StreamAnnotationType', + 'Cluster', + 'GcsSource', + 'OperationMetadata', + 'ClusterInfo', + 'HealthCheckRequest', + 'HealthCheckResponse', + 'AnalysisDefinition', + 'AnalyzerDefinition', + 'AttributeValue', + 'OperatorDefinition', + 'ResourceSpecification', + 'RunStatus', + 'RunMode', + 'Analysis', + 'Operator', + 'Process', + 'BatchRunProcessRequest', + 'BatchRunProcessResponse', + 'CreateAnalysisRequest', + 'CreateOperatorRequest', + 'CreateProcessRequest', + 'DeleteAnalysisRequest', + 'DeleteOperatorRequest', + 'DeleteProcessRequest', + 'GetAnalysisRequest', + 'GetOperatorRequest', + 'GetProcessRequest', + 'ListAnalysesRequest', + 'ListAnalysesResponse', + 'ListOperatorsRequest', + 'ListOperatorsResponse', + 'ListProcessesRequest', + 'ListProcessesResponse', + 'ListPublicOperatorsRequest', + 'ListPublicOperatorsResponse', + 'OperatorQuery', + 'ResolveOperatorInfoRequest', + 'ResolveOperatorInfoResponse', + 'UpdateAnalysisRequest', + 'UpdateOperatorRequest', + 'UpdateProcessRequest', + 'Registry', + 'AddApplicationStreamInputRequest', + 'AddApplicationStreamInputResponse', + 'AIEnabledDevicesInputConfig', + 'Application', + 'ApplicationConfigs', + 'ApplicationInstance', + 'ApplicationNodeAnnotation', + 'ApplicationStreamInput', + 'AutoscalingMetricSpec', + 'BigQueryConfig', + 'CreateApplicationInstancesRequest', + 'CreateApplicationInstancesResponse', + 'CreateApplicationRequest', + 'CreateDraftRequest', + 'CreateProcessorRequest', + 'CustomProcessorSourceInfo', + 'DedicatedResources', + 'DeleteApplicationInstancesRequest', + 'DeleteApplicationInstancesResponse', + 'DeleteApplicationRequest', + 'DeleteDraftRequest', + 'DeleteProcessorRequest', + 'DeployApplicationRequest', + 'DeployApplicationResponse', + 'Draft', + 'GcsOutputConfig', + 'GeneralObjectDetectionConfig', + 'GetApplicationRequest', + 'GetDraftRequest', + 'GetInstanceRequest', + 'GetProcessorRequest', + 'Instance', + 'ListApplicationsRequest', + 'ListApplicationsResponse', + 'ListDraftsRequest', + 'ListDraftsResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListPrebuiltProcessorsRequest', + 'ListPrebuiltProcessorsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'MachineSpec', + 'MediaWarehouseConfig', + 'Node', + 'OccupancyCountConfig', + 'PersonalProtectiveEquipmentDetectionConfig', + 'PersonBlurConfig', + 'PersonVehicleDetectionConfig', + 'Processor', + 'ProcessorConfig', + 'ProcessorIOSpec', + 'ProductRecognizerConfig', + 'RemoveApplicationStreamInputRequest', + 'RemoveApplicationStreamInputResponse', + 'ResourceAnnotations', + 'StreamWithAnnotation', + 'TagParsingConfig', + 'TagRecognizerConfig', + 'UndeployApplicationRequest', + 'UndeployApplicationResponse', + 'UniversalInputConfig', + 'UpdateApplicationInstancesRequest', + 'UpdateApplicationInstancesResponse', + 'UpdateApplicationRequest', + 'UpdateApplicationStreamInputRequest', + 'UpdateApplicationStreamInputResponse', + 'UpdateDraftRequest', + 'UpdateProcessorRequest', + 'VertexAutoMLVideoConfig', + 'VertexAutoMLVisionConfig', + 'VertexCustomConfig', + 'VideoStreamInputConfig', + 'AcceleratorType', + 'DataType', + 'ModelType', + 'GstreamerBufferDescriptor', + 'Packet', + 'PacketHeader', + 'PacketType', + 'RawImageDescriptor', + 'SeriesMetadata', + 'ServerMetadata', + 'AcquireLeaseRequest', + 'CommitRequest', + 'ControlledMode', + 'EagerMode', + 'EventUpdate', + 'Lease', + 'ReceiveEventsControlResponse', + 'ReceiveEventsRequest', + 'ReceiveEventsResponse', + 'ReceivePacketsControlResponse', + 'ReceivePacketsRequest', + 'ReceivePacketsResponse', + 'ReleaseLeaseRequest', + 'ReleaseLeaseResponse', + 'RenewLeaseRequest', + 'RequestMetadata', + 'SendPacketsRequest', + 'SendPacketsResponse', + 'LeaseType', + 'Channel', + 'Event', + 'Series', + 'Stream', + 'CreateClusterRequest', + 'CreateEventRequest', + 'CreateSeriesRequest', + 'CreateStreamRequest', + 'DeleteClusterRequest', + 'DeleteEventRequest', + 'DeleteSeriesRequest', + 'DeleteStreamRequest', + 'GenerateStreamHlsTokenRequest', + 'GenerateStreamHlsTokenResponse', + 'GetClusterRequest', + 'GetEventRequest', + 'GetSeriesRequest', + 'GetStreamRequest', + 'GetStreamThumbnailRequest', + 'GetStreamThumbnailResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListEventsRequest', + 'ListEventsResponse', + 'ListSeriesRequest', + 'ListSeriesResponse', + 'ListStreamsRequest', + 'ListStreamsResponse', + 'MaterializeChannelRequest', + 'UpdateClusterRequest', + 'UpdateEventRequest', + 'UpdateSeriesRequest', + 'UpdateStreamRequest', + 'AddCollectionItemRequest', + 'AddCollectionItemResponse', + 'AnalyzeAssetMetadata', + 'AnalyzeAssetRequest', + 'AnalyzeAssetResponse', + 'AnalyzeCorpusMetadata', + 'AnalyzeCorpusRequest', + 'AnalyzeCorpusResponse', + 'Annotation', + 'AnnotationCustomizedStruct', + 'AnnotationList', + 'AnnotationMatchingResult', + 'AnnotationValue', + 'Asset', + 'AssetSource', + 'BoolValue', + 'CircleArea', + 'ClipAssetRequest', + 'ClipAssetResponse', + 'Collection', + 'CollectionItem', + 'Corpus', + 'CreateAnnotationRequest', + 'CreateAssetRequest', + 'CreateCollectionMetadata', + 'CreateCollectionRequest', + 'CreateCorpusMetadata', + 'CreateCorpusRequest', + 'CreateDataSchemaRequest', + 'CreateIndexEndpointMetadata', + 'CreateIndexEndpointRequest', + 'CreateIndexMetadata', + 'CreateIndexRequest', + 'CreateSearchConfigRequest', + 'CreateSearchHypernymRequest', + 'Criteria', + 'DataSchema', + 'DataSchemaDetails', + 'DateTimeRange', + 'DateTimeRangeArray', + 'DeleteAnnotationRequest', + 'DeleteAssetMetadata', + 'DeleteAssetRequest', + 'DeleteCollectionMetadata', + 'DeleteCollectionRequest', + 'DeleteCorpusRequest', + 'DeleteDataSchemaRequest', + 'DeleteIndexEndpointMetadata', + 'DeleteIndexEndpointRequest', + 'DeleteIndexMetadata', + 'DeleteIndexRequest', + 'DeleteSearchConfigRequest', + 'DeleteSearchHypernymRequest', + 'DeployedIndex', + 'DeployedIndexReference', + 'DeployIndexMetadata', + 'DeployIndexRequest', + 'DeployIndexResponse', + 'FacetBucket', + 'FacetGroup', + 'FacetProperty', + 'FacetValue', + 'FloatRange', + 'FloatRangeArray', + 'GenerateHlsUriRequest', + 'GenerateHlsUriResponse', + 'GenerateRetrievalUrlRequest', + 'GenerateRetrievalUrlResponse', + 'GeoCoordinate', + 'GeoLocationArray', + 'GetAnnotationRequest', + 'GetAssetRequest', + 'GetCollectionRequest', + 'GetCorpusRequest', + 'GetDataSchemaRequest', + 'GetIndexEndpointRequest', + 'GetIndexRequest', + 'GetSearchConfigRequest', + 'GetSearchHypernymRequest', + 'ImageQuery', + 'ImportAssetsMetadata', + 'ImportAssetsRequest', + 'ImportAssetsResponse', + 'Index', + 'IndexAssetMetadata', + 'IndexAssetRequest', + 'IndexAssetResponse', + 'IndexedAsset', + 'IndexEndpoint', + 'IndexingStatus', + 'IngestAssetRequest', + 'IngestAssetResponse', + 'IntRange', + 'IntRangeArray', + 'ListAnnotationsRequest', + 'ListAnnotationsResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListCollectionsRequest', + 'ListCollectionsResponse', + 'ListCorporaRequest', + 'ListCorporaResponse', + 'ListDataSchemasRequest', + 'ListDataSchemasResponse', + 'ListIndexEndpointsRequest', + 'ListIndexEndpointsResponse', + 'ListIndexesRequest', + 'ListIndexesResponse', + 'ListSearchConfigsRequest', + 'ListSearchConfigsResponse', + 'ListSearchHypernymsRequest', + 'ListSearchHypernymsResponse', + 'Partition', + 'RemoveCollectionItemRequest', + 'RemoveCollectionItemResponse', + 'RemoveIndexAssetMetadata', + 'RemoveIndexAssetRequest', + 'RemoveIndexAssetResponse', + 'SchemaKeySortingStrategy', + 'SearchAssetsRequest', + 'SearchAssetsResponse', + 'SearchCapability', + 'SearchCapabilitySetting', + 'SearchConfig', + 'SearchCriteriaProperty', + 'SearchHypernym', + 'SearchIndexEndpointRequest', + 'SearchIndexEndpointResponse', + 'SearchResultItem', + 'StringArray', + 'UndeployIndexMetadata', + 'UndeployIndexRequest', + 'UndeployIndexResponse', + 'UpdateAnnotationRequest', + 'UpdateAssetRequest', + 'UpdateCollectionRequest', + 'UpdateCorpusRequest', + 'UpdateDataSchemaRequest', + 'UpdateIndexEndpointMetadata', + 'UpdateIndexEndpointRequest', + 'UpdateIndexMetadata', + 'UpdateIndexRequest', + 'UpdateSearchConfigRequest', + 'UpdateSearchHypernymRequest', + 'UploadAssetMetadata', + 'UploadAssetRequest', + 'UploadAssetResponse', + 'UserSpecifiedAnnotation', + 'ViewCollectionItemsRequest', + 'ViewCollectionItemsResponse', + 'ViewIndexedAssetsRequest', + 'ViewIndexedAssetsResponse', + 'FacetBucketType', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/annotations.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/annotations.py new file mode 100644 index 000000000000..032deb1e2f09 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/annotations.py @@ -0,0 +1,1453 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'StreamAnnotationType', + 'PersonalProtectiveEquipmentDetectionOutput', + 'ObjectDetectionPredictionResult', + 'ImageObjectDetectionPredictionResult', + 'ClassificationPredictionResult', + 'ImageSegmentationPredictionResult', + 'VideoActionRecognitionPredictionResult', + 'VideoObjectTrackingPredictionResult', + 'VideoClassificationPredictionResult', + 'OccupancyCountingPredictionResult', + 'StreamAnnotation', + 'StreamAnnotations', + 'NormalizedPolygon', + 'NormalizedPolyline', + 'NormalizedVertex', + 'AppPlatformMetadata', + 'AppPlatformCloudFunctionRequest', + 'AppPlatformCloudFunctionResponse', + 'AppPlatformEventBody', + }, +) + + +class StreamAnnotationType(proto.Enum): + r"""Enum describing all possible types of a stream annotation. + + Values: + STREAM_ANNOTATION_TYPE_UNSPECIFIED (0): + Type UNSPECIFIED. + STREAM_ANNOTATION_TYPE_ACTIVE_ZONE (1): + active_zone annotation defines a polygon on top of the + content from an image/video based stream, following + processing will only focus on the content inside the active + zone. + STREAM_ANNOTATION_TYPE_CROSSING_LINE (2): + crossing_line annotation defines a polyline on top of the + content from an image/video based Vision AI stream, events + happening across the line will be captured. For example, the + counts of people who goes acroos the line in Occupancy + Analytic Processor. + """ + STREAM_ANNOTATION_TYPE_UNSPECIFIED = 0 + STREAM_ANNOTATION_TYPE_ACTIVE_ZONE = 1 + STREAM_ANNOTATION_TYPE_CROSSING_LINE = 2 + + +class PersonalProtectiveEquipmentDetectionOutput(proto.Message): + r"""Output format for Personal Protective Equipment Detection + Operator. + + Attributes: + current_time (google.protobuf.timestamp_pb2.Timestamp): + Current timestamp. + detected_persons (MutableSequence[google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionOutput.DetectedPerson]): + A list of DetectedPersons. + """ + + class PersonEntity(proto.Message): + r"""The entity info for annotations from person detection + prediction result. + + Attributes: + person_entity_id (int): + Entity id. + """ + + person_entity_id: int = proto.Field( + proto.INT64, + number=1, + ) + + class PPEEntity(proto.Message): + r"""The entity info for annotations from PPE detection prediction + result. + + Attributes: + ppe_label_id (int): + Label id. + ppe_label_string (str): + Human readable string of the label (Examples: + helmet, glove, mask). + ppe_supercategory_label_string (str): + Human readable string of the super category label (Examples: + head_cover, hands_cover, face_cover). + ppe_entity_id (int): + Entity id. + """ + + ppe_label_id: int = proto.Field( + proto.INT64, + number=1, + ) + ppe_label_string: str = proto.Field( + proto.STRING, + number=2, + ) + ppe_supercategory_label_string: str = proto.Field( + proto.STRING, + number=3, + ) + ppe_entity_id: int = proto.Field( + proto.INT64, + number=4, + ) + + class NormalizedBoundingBox(proto.Message): + r"""Bounding Box in the normalized coordinates. + + Attributes: + xmin (float): + Min in x coordinate. + ymin (float): + Min in y coordinate. + width (float): + Width of the bounding box. + height (float): + Height of the bounding box. + """ + + xmin: float = proto.Field( + proto.FLOAT, + number=1, + ) + ymin: float = proto.Field( + proto.FLOAT, + number=2, + ) + width: float = proto.Field( + proto.FLOAT, + number=3, + ) + height: float = proto.Field( + proto.FLOAT, + number=4, + ) + + class PersonIdentifiedBox(proto.Message): + r"""PersonIdentified box contains the location and the entity + info of the person. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + confidence_score (float): + Confidence score associated with this box. + person_entity (google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionOutput.PersonEntity): + Person entity info. + """ + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox', + ) + confidence_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + person_entity: 'PersonalProtectiveEquipmentDetectionOutput.PersonEntity' = proto.Field( + proto.MESSAGE, + number=4, + message='PersonalProtectiveEquipmentDetectionOutput.PersonEntity', + ) + + class PPEIdentifiedBox(proto.Message): + r"""PPEIdentified box contains the location and the entity info + of the PPE. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + confidence_score (float): + Confidence score associated with this box. + ppe_entity (google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionOutput.PPEEntity): + PPE entity info. + """ + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox', + ) + confidence_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + ppe_entity: 'PersonalProtectiveEquipmentDetectionOutput.PPEEntity' = proto.Field( + proto.MESSAGE, + number=4, + message='PersonalProtectiveEquipmentDetectionOutput.PPEEntity', + ) + + class DetectedPerson(proto.Message): + r"""Detected Person contains the detected person and their + associated ppes and their protecting information. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + person_id (int): + The id of detected person. + detected_person_identified_box (google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionOutput.PersonIdentifiedBox): + The info of detected person identified box. + detected_ppe_identified_boxes (MutableSequence[google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionOutput.PPEIdentifiedBox]): + The info of detected person associated ppe + identified boxes. + face_coverage_score (float): + Coverage score for each body part. + Coverage score for face. + + This field is a member of `oneof`_ ``_face_coverage_score``. + eyes_coverage_score (float): + Coverage score for eyes. + + This field is a member of `oneof`_ ``_eyes_coverage_score``. + head_coverage_score (float): + Coverage score for head. + + This field is a member of `oneof`_ ``_head_coverage_score``. + hands_coverage_score (float): + Coverage score for hands. + + This field is a member of `oneof`_ ``_hands_coverage_score``. + body_coverage_score (float): + Coverage score for body. + + This field is a member of `oneof`_ ``_body_coverage_score``. + feet_coverage_score (float): + Coverage score for feet. + + This field is a member of `oneof`_ ``_feet_coverage_score``. + """ + + person_id: int = proto.Field( + proto.INT64, + number=1, + ) + detected_person_identified_box: 'PersonalProtectiveEquipmentDetectionOutput.PersonIdentifiedBox' = proto.Field( + proto.MESSAGE, + number=2, + message='PersonalProtectiveEquipmentDetectionOutput.PersonIdentifiedBox', + ) + detected_ppe_identified_boxes: MutableSequence['PersonalProtectiveEquipmentDetectionOutput.PPEIdentifiedBox'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='PersonalProtectiveEquipmentDetectionOutput.PPEIdentifiedBox', + ) + face_coverage_score: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + eyes_coverage_score: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + head_coverage_score: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + hands_coverage_score: float = proto.Field( + proto.FLOAT, + number=7, + optional=True, + ) + body_coverage_score: float = proto.Field( + proto.FLOAT, + number=8, + optional=True, + ) + feet_coverage_score: float = proto.Field( + proto.FLOAT, + number=9, + optional=True, + ) + + current_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + detected_persons: MutableSequence[DetectedPerson] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=DetectedPerson, + ) + + +class ObjectDetectionPredictionResult(proto.Message): + r"""Prediction output format for Generic Object Detection. + + Attributes: + current_time (google.protobuf.timestamp_pb2.Timestamp): + Current timestamp. + identified_boxes (MutableSequence[google.cloud.visionai_v1.types.ObjectDetectionPredictionResult.IdentifiedBox]): + A list of identified boxes. + """ + + class Entity(proto.Message): + r"""The entity info for annotations from object detection + prediction result. + + Attributes: + label_id (int): + Label id. + label_string (str): + Human readable string of the label. + """ + + label_id: int = proto.Field( + proto.INT64, + number=1, + ) + label_string: str = proto.Field( + proto.STRING, + number=2, + ) + + class IdentifiedBox(proto.Message): + r"""Identified box contains location and the entity of the + object. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1.types.ObjectDetectionPredictionResult.IdentifiedBox.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + confidence_score (float): + Confidence score associated with this box. + entity (google.cloud.visionai_v1.types.ObjectDetectionPredictionResult.Entity): + Entity of this box. + """ + + class NormalizedBoundingBox(proto.Message): + r"""Bounding Box in the normalized coordinates. + + Attributes: + xmin (float): + Min in x coordinate. + ymin (float): + Min in y coordinate. + width (float): + Width of the bounding box. + height (float): + Height of the bounding box. + """ + + xmin: float = proto.Field( + proto.FLOAT, + number=1, + ) + ymin: float = proto.Field( + proto.FLOAT, + number=2, + ) + width: float = proto.Field( + proto.FLOAT, + number=3, + ) + height: float = proto.Field( + proto.FLOAT, + number=4, + ) + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'ObjectDetectionPredictionResult.IdentifiedBox.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='ObjectDetectionPredictionResult.IdentifiedBox.NormalizedBoundingBox', + ) + confidence_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + entity: 'ObjectDetectionPredictionResult.Entity' = proto.Field( + proto.MESSAGE, + number=4, + message='ObjectDetectionPredictionResult.Entity', + ) + + current_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + identified_boxes: MutableSequence[IdentifiedBox] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=IdentifiedBox, + ) + + +class ImageObjectDetectionPredictionResult(proto.Message): + r"""Prediction output format for Image Object Detection. + + Attributes: + ids (MutableSequence[int]): + The resource IDs of the AnnotationSpecs that + had been identified, ordered by the confidence + score descendingly. It is the id segment instead + of full resource name. + display_names (MutableSequence[str]): + The display names of the AnnotationSpecs that + had been identified, order matches the IDs. + confidences (MutableSequence[float]): + The Model's confidences in correctness of the + predicted IDs, higher value means higher + confidence. Order matches the Ids. + bboxes (MutableSequence[google.protobuf.struct_pb2.ListValue]): + Bounding boxes, i.e. the rectangles over the image, that + pinpoint the found AnnotationSpecs. Given in order that + matches the IDs. Each bounding box is an array of 4 numbers + ``xMin``, ``xMax``, ``yMin``, and ``yMax``, which represent + the extremal coordinates of the box. They are relative to + the image size, and the point 0,0 is in the top left of the + image. + """ + + ids: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=1, + ) + display_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + confidences: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=3, + ) + bboxes: MutableSequence[struct_pb2.ListValue] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=struct_pb2.ListValue, + ) + + +class ClassificationPredictionResult(proto.Message): + r"""Prediction output format for Image and Text Classification. + + Attributes: + ids (MutableSequence[int]): + The resource IDs of the AnnotationSpecs that + had been identified. + display_names (MutableSequence[str]): + The display names of the AnnotationSpecs that + had been identified, order matches the IDs. + confidences (MutableSequence[float]): + The Model's confidences in correctness of the + predicted IDs, higher value means higher + confidence. Order matches the Ids. + """ + + ids: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=1, + ) + display_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + confidences: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=3, + ) + + +class ImageSegmentationPredictionResult(proto.Message): + r"""Prediction output format for Image Segmentation. + + Attributes: + category_mask (str): + A PNG image where each pixel in the mask + represents the category in which the pixel in + the original image was predicted to belong to. + The size of this image will be the same as the + original image. The mapping between the + AnntoationSpec and the color can be found in + model's metadata. The model will choose the most + likely category and if none of the categories + reach the confidence threshold, the pixel will + be marked as background. + confidence_mask (str): + A one channel image which is encoded as an + 8bit lossless PNG. The size of the image will be + the same as the original image. For a specific + pixel, darker color means less confidence in + correctness of the cateogry in the categoryMask + for the corresponding pixel. Black means no + confidence and white means complete confidence. + """ + + category_mask: str = proto.Field( + proto.STRING, + number=1, + ) + confidence_mask: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VideoActionRecognitionPredictionResult(proto.Message): + r"""Prediction output format for Video Action Recognition. + + Attributes: + segment_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning, inclusive, of the video's time + segment in which the actions have been + identified. + segment_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end, inclusive, of the video's time + segment in which the actions have been + identified. Particularly, if the end is the same + as the start, it means the identification + happens on a specific video frame. + actions (MutableSequence[google.cloud.visionai_v1.types.VideoActionRecognitionPredictionResult.IdentifiedAction]): + All of the actions identified in the time + range. + """ + + class IdentifiedAction(proto.Message): + r"""Each IdentifiedAction is one particular identification of an action + specified with the AnnotationSpec id, display_name and the + associated confidence score. + + Attributes: + id (str): + The resource ID of the AnnotationSpec that + had been identified. + display_name (str): + The display name of the AnnotationSpec that + had been identified. + confidence (float): + The Model's confidence in correction of this + identification, higher value means higher + confidence. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=3, + ) + + segment_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + segment_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + actions: MutableSequence[IdentifiedAction] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=IdentifiedAction, + ) + + +class VideoObjectTrackingPredictionResult(proto.Message): + r"""Prediction output format for Video Object Tracking. + + Attributes: + segment_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning, inclusive, of the video's time + segment in which the current identifications + happens. + segment_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end, inclusive, of the video's time + segment in which the current identifications + happen. Particularly, if the end is the same as + the start, it means the identifications happen + on a specific video frame. + objects (MutableSequence[google.cloud.visionai_v1.types.VideoObjectTrackingPredictionResult.DetectedObject]): + All of the objects detected in the specified + time range. + """ + + class BoundingBox(proto.Message): + r"""Boundingbox for detected object. I.e. the rectangle over the + video frame pinpointing the found AnnotationSpec. The + coordinates are relative to the frame size, and the point 0,0 is + in the top left of the frame. + + Attributes: + x_min (float): + The leftmost coordinate of the bounding box. + x_max (float): + The rightmost coordinate of the bounding box. + y_min (float): + The topmost coordinate of the bounding box. + y_max (float): + The bottommost coordinate of the bounding + box. + """ + + x_min: float = proto.Field( + proto.FLOAT, + number=1, + ) + x_max: float = proto.Field( + proto.FLOAT, + number=2, + ) + y_min: float = proto.Field( + proto.FLOAT, + number=3, + ) + y_max: float = proto.Field( + proto.FLOAT, + number=4, + ) + + class DetectedObject(proto.Message): + r"""Each DetectedObject is one particular identification of an object + specified with the AnnotationSpec id and display_name, the bounding + box, the associated confidence score and the corresponding track_id. + + Attributes: + id (str): + The resource ID of the AnnotationSpec that + had been identified. + display_name (str): + The display name of the AnnotationSpec that + had been identified. + bounding_box (google.cloud.visionai_v1.types.VideoObjectTrackingPredictionResult.BoundingBox): + Boundingbox. + confidence (float): + The Model's confidence in correction of this + identification, higher value means higher + confidence. + track_id (int): + The same object may be identified on muitiple frames which + are typical adjacent. The set of frames where a particular + object has been detected form a track. This track_id can be + used to trace down all frames for an detected object. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + bounding_box: 'VideoObjectTrackingPredictionResult.BoundingBox' = proto.Field( + proto.MESSAGE, + number=3, + message='VideoObjectTrackingPredictionResult.BoundingBox', + ) + confidence: float = proto.Field( + proto.FLOAT, + number=4, + ) + track_id: int = proto.Field( + proto.INT64, + number=5, + ) + + segment_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + segment_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + objects: MutableSequence[DetectedObject] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=DetectedObject, + ) + + +class VideoClassificationPredictionResult(proto.Message): + r"""Prediction output format for Video Classification. + + Attributes: + segment_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning, inclusive, of the video's time + segment in which the classifications have been + identified. + segment_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end, inclusive, of the video's time + segment in which the classifications have been + identified. Particularly, if the end is the same + as the start, it means the identification + happens on a specific video frame. + classifications (MutableSequence[google.cloud.visionai_v1.types.VideoClassificationPredictionResult.IdentifiedClassification]): + All of the classifications identified in the + time range. + """ + + class IdentifiedClassification(proto.Message): + r"""Each IdentifiedClassification is one particular identification of an + classification specified with the AnnotationSpec id and + display_name, and the associated confidence score. + + Attributes: + id (str): + The resource ID of the AnnotationSpec that + had been identified. + display_name (str): + The display name of the AnnotationSpec that + had been identified. + confidence (float): + The Model's confidence in correction of this + identification, higher value means higher + confidence. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=3, + ) + + segment_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + segment_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + classifications: MutableSequence[IdentifiedClassification] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=IdentifiedClassification, + ) + + +class OccupancyCountingPredictionResult(proto.Message): + r"""The prediction result proto for occupancy counting. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + current_time (google.protobuf.timestamp_pb2.Timestamp): + Current timestamp. + identified_boxes (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.IdentifiedBox]): + A list of identified boxes. + stats (google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats): + Detection statistics. + track_info (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.TrackInfo]): + Track related information. All the tracks + that are live at this timestamp. It only exists + if tracking is enabled. + dwell_time_info (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.DwellTimeInfo]): + Dwell time related information. All the + tracks that are live in a given zone with a + start and end dwell time timestamp + pts (int): + The presentation timestamp of the frame. + + This field is a member of `oneof`_ ``_pts``. + """ + + class Entity(proto.Message): + r"""The entity info for annotations from occupancy counting + operator. + + Attributes: + label_id (int): + Label id. + label_string (str): + Human readable string of the label. + """ + + label_id: int = proto.Field( + proto.INT64, + number=1, + ) + label_string: str = proto.Field( + proto.STRING, + number=2, + ) + + class IdentifiedBox(proto.Message): + r"""Identified box contains location and the entity of the + object. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.IdentifiedBox.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + score (float): + Confidence score associated with this box. + entity (google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Entity): + Entity of this box. + track_id (int): + An unique id to identify a track. It should + be consistent across frames. It only exists if + tracking is enabled. + """ + + class NormalizedBoundingBox(proto.Message): + r"""Bounding Box in the normalized coordinates. + + Attributes: + xmin (float): + Min in x coordinate. + ymin (float): + Min in y coordinate. + width (float): + Width of the bounding box. + height (float): + Height of the bounding box. + """ + + xmin: float = proto.Field( + proto.FLOAT, + number=1, + ) + ymin: float = proto.Field( + proto.FLOAT, + number=2, + ) + width: float = proto.Field( + proto.FLOAT, + number=3, + ) + height: float = proto.Field( + proto.FLOAT, + number=4, + ) + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'OccupancyCountingPredictionResult.IdentifiedBox.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.IdentifiedBox.NormalizedBoundingBox', + ) + score: float = proto.Field( + proto.FLOAT, + number=3, + ) + entity: 'OccupancyCountingPredictionResult.Entity' = proto.Field( + proto.MESSAGE, + number=4, + message='OccupancyCountingPredictionResult.Entity', + ) + track_id: int = proto.Field( + proto.INT64, + number=5, + ) + + class Stats(proto.Message): + r"""The statistics info for annotations from occupancy counting + operator. + + Attributes: + full_frame_count (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + Counts of the full frame. + crossing_line_counts (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.CrossingLineCount]): + Crossing line counts. + active_zone_counts (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.ActiveZoneCount]): + Active zone counts. + """ + + class ObjectCount(proto.Message): + r"""The object info and instant count for annotations from + occupancy counting operator. + + Attributes: + entity (google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Entity): + Entity of this object. + count (int): + Count of the object. + """ + + entity: 'OccupancyCountingPredictionResult.Entity' = proto.Field( + proto.MESSAGE, + number=1, + message='OccupancyCountingPredictionResult.Entity', + ) + count: int = proto.Field( + proto.INT32, + number=2, + ) + + class AccumulatedObjectCount(proto.Message): + r"""The object info and accumulated count for annotations from + occupancy counting operator. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start time of the accumulated count. + object_count (google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.ObjectCount): + The object count for the accumulated count. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + object_count: 'OccupancyCountingPredictionResult.Stats.ObjectCount' = proto.Field( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + + class CrossingLineCount(proto.Message): + r"""Message for Crossing line count. + + Attributes: + annotation (google.cloud.visionai_v1.types.StreamAnnotation): + Line annotation from the user. + positive_direction_counts (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + The direction that follows the right hand + rule. + negative_direction_counts (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + The direction that is opposite to the right + hand rule. + accumulated_positive_direction_counts (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount]): + The accumulated positive count. + accumulated_negative_direction_counts (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount]): + The accumulated negative count. + """ + + annotation: 'StreamAnnotation' = proto.Field( + proto.MESSAGE, + number=1, + message='StreamAnnotation', + ) + positive_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + negative_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + accumulated_positive_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount', + ) + accumulated_negative_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount', + ) + + class ActiveZoneCount(proto.Message): + r"""Message for the active zone count. + + Attributes: + annotation (google.cloud.visionai_v1.types.StreamAnnotation): + Active zone annotation from the user. + counts (MutableSequence[google.cloud.visionai_v1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + Counts in the zone. + """ + + annotation: 'StreamAnnotation' = proto.Field( + proto.MESSAGE, + number=1, + message='StreamAnnotation', + ) + counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + + full_frame_count: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + crossing_line_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.CrossingLineCount'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.CrossingLineCount', + ) + active_zone_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ActiveZoneCount'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='OccupancyCountingPredictionResult.Stats.ActiveZoneCount', + ) + + class TrackInfo(proto.Message): + r"""The track info for annotations from occupancy counting + operator. + + Attributes: + track_id (str): + An unique id to identify a track. It should + be consistent across frames. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start timestamp of this track. + """ + + track_id: str = proto.Field( + proto.STRING, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class DwellTimeInfo(proto.Message): + r"""The dwell time info for annotations from occupancy counting + operator. + + Attributes: + track_id (str): + An unique id to identify a track. It should + be consistent across frames. + zone_id (str): + The unique id for the zone in which the + object is dwelling/waiting. + dwell_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning time when a dwelling object has + been identified in a zone. + dwell_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end time when a dwelling object has + exited in a zone. + """ + + track_id: str = proto.Field( + proto.STRING, + number=1, + ) + zone_id: str = proto.Field( + proto.STRING, + number=2, + ) + dwell_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + dwell_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + current_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + identified_boxes: MutableSequence[IdentifiedBox] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=IdentifiedBox, + ) + stats: Stats = proto.Field( + proto.MESSAGE, + number=3, + message=Stats, + ) + track_info: MutableSequence[TrackInfo] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=TrackInfo, + ) + dwell_time_info: MutableSequence[DwellTimeInfo] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=DwellTimeInfo, + ) + pts: int = proto.Field( + proto.INT64, + number=6, + optional=True, + ) + + +class StreamAnnotation(proto.Message): + r"""message about annotations about Vision AI stream resource. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + active_zone (google.cloud.visionai_v1.types.NormalizedPolygon): + Annotation for type ACTIVE_ZONE + + This field is a member of `oneof`_ ``annotation_payload``. + crossing_line (google.cloud.visionai_v1.types.NormalizedPolyline): + Annotation for type CROSSING_LINE + + This field is a member of `oneof`_ ``annotation_payload``. + id (str): + ID of the annotation. It must be unique when + used in the certain context. For example, all + the annotations to one input streams of a Vision + AI application. + display_name (str): + User-friendly name for the annotation. + source_stream (str): + The Vision AI stream resource name. + type_ (google.cloud.visionai_v1.types.StreamAnnotationType): + The actual type of Annotation. + """ + + active_zone: 'NormalizedPolygon' = proto.Field( + proto.MESSAGE, + number=5, + oneof='annotation_payload', + message='NormalizedPolygon', + ) + crossing_line: 'NormalizedPolyline' = proto.Field( + proto.MESSAGE, + number=6, + oneof='annotation_payload', + message='NormalizedPolyline', + ) + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + source_stream: str = proto.Field( + proto.STRING, + number=3, + ) + type_: 'StreamAnnotationType' = proto.Field( + proto.ENUM, + number=4, + enum='StreamAnnotationType', + ) + + +class StreamAnnotations(proto.Message): + r"""A wrapper of repeated StreamAnnotation. + + Attributes: + stream_annotations (MutableSequence[google.cloud.visionai_v1.types.StreamAnnotation]): + Multiple annotations. + """ + + stream_annotations: MutableSequence['StreamAnnotation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='StreamAnnotation', + ) + + +class NormalizedPolygon(proto.Message): + r"""Normalized Polygon. + + Attributes: + normalized_vertices (MutableSequence[google.cloud.visionai_v1.types.NormalizedVertex]): + The bounding polygon normalized vertices. Top left corner of + the image will be [0, 0]. + """ + + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class NormalizedPolyline(proto.Message): + r"""Normalized Pplyline, which represents a curve consisting of + connected straight-line segments. + + Attributes: + normalized_vertices (MutableSequence[google.cloud.visionai_v1.types.NormalizedVertex]): + A sequence of vertices connected by straight + lines. + """ + + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x: float = proto.Field( + proto.FLOAT, + number=1, + ) + y: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class AppPlatformMetadata(proto.Message): + r"""Message of essential metadata of App Platform. + This message is usually attached to a certain processor output + annotation for customer to identify the source of the data. + + Attributes: + application (str): + The application resource name. + instance_id (str): + The instance resource id. Instance is the + nested resource of application under collection + 'instances'. + node (str): + The node name of the application graph. + processor (str): + The referred processor resource name of the + application node. + """ + + application: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + node: str = proto.Field( + proto.STRING, + number=3, + ) + processor: str = proto.Field( + proto.STRING, + number=4, + ) + + +class AppPlatformCloudFunctionRequest(proto.Message): + r"""For any cloud function based customer processing logic, + customer's cloud function is expected to receive + AppPlatformCloudFunctionRequest as request and send back + AppPlatformCloudFunctionResponse as response. Message of request + from AppPlatform to Cloud Function. + + Attributes: + app_platform_metadata (google.cloud.visionai_v1.types.AppPlatformMetadata): + The metadata of the AppPlatform for customer + to identify the source of the payload. + annotations (MutableSequence[google.cloud.visionai_v1.types.AppPlatformCloudFunctionRequest.StructedInputAnnotation]): + The actual annotations to be processed by the + customized Cloud Function. + """ + + class StructedInputAnnotation(proto.Message): + r"""A general annotation message that uses struct format to + represent different concrete annotation protobufs. + + Attributes: + ingestion_time_micros (int): + The ingestion time of the current annotation. + annotation (google.protobuf.struct_pb2.Struct): + The struct format of the actual annotation. + """ + + ingestion_time_micros: int = proto.Field( + proto.INT64, + number=1, + ) + annotation: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + + app_platform_metadata: 'AppPlatformMetadata' = proto.Field( + proto.MESSAGE, + number=1, + message='AppPlatformMetadata', + ) + annotations: MutableSequence[StructedInputAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=StructedInputAnnotation, + ) + + +class AppPlatformCloudFunctionResponse(proto.Message): + r"""Message of the response from customer's Cloud Function to + AppPlatform. + + Attributes: + annotations (MutableSequence[google.cloud.visionai_v1.types.AppPlatformCloudFunctionResponse.StructedOutputAnnotation]): + The modified annotations that is returned + back to AppPlatform. If the annotations fields + are empty, then those annotations will be + dropped by AppPlatform. + annotation_passthrough (bool): + If set to true, AppPlatform will use original + annotations instead of dropping them, even if it + is empty in the annotations filed. + events (MutableSequence[google.cloud.visionai_v1.types.AppPlatformEventBody]): + The event notifications that is returned back + to AppPlatform. Typically it will then be + configured to be consumed/forwared to a operator + that handles events, such as Pub/Sub operator. + """ + + class StructedOutputAnnotation(proto.Message): + r"""A general annotation message that uses struct format to + represent different concrete annotation protobufs. + + Attributes: + annotation (google.protobuf.struct_pb2.Struct): + The struct format of the actual annotation. + """ + + annotation: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + annotations: MutableSequence[StructedOutputAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=StructedOutputAnnotation, + ) + annotation_passthrough: bool = proto.Field( + proto.BOOL, + number=3, + ) + events: MutableSequence['AppPlatformEventBody'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AppPlatformEventBody', + ) + + +class AppPlatformEventBody(proto.Message): + r"""Message of content of appPlatform event + + Attributes: + event_message (str): + Human readable string of the event like + "There are more than 6 people in the scene". or + "Shelf is empty!". + payload (google.protobuf.struct_pb2.Struct): + For the case of Pub/Sub, it will be stored in + the message attributes. ​​pubsub.proto + event_id (str): + User defined Event Id, used to classify event, within a + delivery interval, events from the same application instance + with the same id will be de-duplicated & only first one will + be sent out. Empty event_id will be treated as "". + """ + + event_message: str = proto.Field( + proto.STRING, + number=1, + ) + payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + event_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/common.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/common.py new file mode 100644 index 000000000000..3089d5b8927a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/common.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'Cluster', + 'OperationMetadata', + 'GcsSource', + }, +) + + +class Cluster(proto.Message): + r"""Message describing the Cluster object. + + Attributes: + name (str): + Output only. Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + dataplane_service_endpoint (str): + Output only. The DNS name of the data plane + service + state (google.cloud.visionai_v1.types.Cluster.State): + Output only. The current state of the + cluster. + psc_target (str): + Output only. The private service connection + service target name. + """ + class State(proto.Enum): + r"""The current state of the cluster. + + Values: + STATE_UNSPECIFIED (0): + Not set. + PROVISIONING (1): + The PROVISIONING state indicates the cluster + is being created. + RUNNING (2): + The RUNNING state indicates the cluster has + been created and is fully usable. + STOPPING (3): + The STOPPING state indicates the cluster is + being deleted. + ERROR (4): + The ERROR state indicates the cluster is + unusable. It will be automatically deleted. + """ + STATE_UNSPECIFIED = 0 + PROVISIONING = 1 + RUNNING = 2 + STOPPING = 3 + ERROR = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + dataplane_service_endpoint: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + psc_target: str = proto.Field( + proto.STRING, + number=8, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location for the input content. + + Attributes: + uris (MutableSequence[str]): + Required. References to a Google Cloud + Storage paths. + """ + + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/health_service.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/health_service.py new file mode 100644 index 000000000000..f9cb03dc141f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/health_service.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'HealthCheckRequest', + 'HealthCheckResponse', + 'ClusterInfo', + }, +) + + +class HealthCheckRequest(proto.Message): + r"""HealthCheckRequest is the request message for Check. + + Attributes: + cluster (str): + The parent of the resource. + """ + + cluster: str = proto.Field( + proto.STRING, + number=1, + ) + + +class HealthCheckResponse(proto.Message): + r"""HealthCheckResponse is the response message for Check. + + Attributes: + healthy (bool): + Indicates whether the cluster is in healthy + state or not. + reason (str): + Reason of why the cluster is in unhealthy + state. + cluster_info (google.cloud.visionai_v1.types.ClusterInfo): + Other information of the cluster client may + be interested. + """ + + healthy: bool = proto.Field( + proto.BOOL, + number=1, + ) + reason: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_info: 'ClusterInfo' = proto.Field( + proto.MESSAGE, + number=3, + message='ClusterInfo', + ) + + +class ClusterInfo(proto.Message): + r""" + + Attributes: + streams_count (int): + The number of active streams in the cluster. + processes_count (int): + The number of active processes in the + cluster. + """ + + streams_count: int = proto.Field( + proto.INT32, + number=1, + ) + processes_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva.py new file mode 100644 index 000000000000..b703b9a1cb44 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'RunMode', + 'OperatorDefinition', + 'ResourceSpecification', + 'AttributeValue', + 'AnalyzerDefinition', + 'AnalysisDefinition', + 'RunStatus', + }, +) + + +class RunMode(proto.Enum): + r"""RunMode represents the mode to launch the Process on. + + Values: + RUN_MODE_UNSPECIFIED (0): + Mode is unspecified. + LIVE (1): + Live mode. Meaning the Process is launched to + handle live video source, and possible packet + drops are expected. + SUBMISSION (2): + Submission mode. Meaning the Process is + launched to handle bounded video files, with no + packet drop. Completion status is tracked. + """ + RUN_MODE_UNSPECIFIED = 0 + LIVE = 1 + SUBMISSION = 2 + + +class OperatorDefinition(proto.Message): + r"""Defines the interface of an Operator. + + Arguments to an operator are input/output streams that are + getting processesed/returned while attributes are fixed + configuration parameters. + + Attributes: + operator (str): + The name of this operator. + + Tentatively [A-Z][a-zA-Z0-9]*, e.g., BboxCounter, + PetDetector, PetDetector1. + input_args (MutableSequence[google.cloud.visionai_v1.types.OperatorDefinition.ArgumentDefinition]): + Declares input arguments. + output_args (MutableSequence[google.cloud.visionai_v1.types.OperatorDefinition.ArgumentDefinition]): + Declares output arguments. + attributes (MutableSequence[google.cloud.visionai_v1.types.OperatorDefinition.AttributeDefinition]): + Declares the attributes. + resources (google.cloud.visionai_v1.types.ResourceSpecification): + The resources for running the operator. + short_description (str): + Short description of the operator. + description (str): + Full description of the operator. + """ + + class ArgumentDefinition(proto.Message): + r"""Defines an argument to an operator. + + Used for both inputs and outputs. + + Attributes: + argument (str): + The name of the argument. + + Tentatively `a-z <[_a-z0-9]*[a-z0-9]>`__?, e.g., video, + audio, high_fps_frame. + type_ (str): + The data type of the argument. + + This should match the textual representation of + a stream/Packet type. + """ + + argument: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + + class AttributeDefinition(proto.Message): + r"""Defines an attribute of an operator. + + Attributes: + attribute (str): + The name of the attribute. + + Tentatively `a-z <[_a-z0-9]*[a-z0-9]>`__?, e.g., + max_frames_per_video, resize_height. + type_ (str): + The type of this attribute. + + See attribute_value.proto for possibilities. + default_value (google.cloud.visionai_v1.types.AttributeValue): + The default value for the attribute. + """ + + attribute: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + default_value: 'AttributeValue' = proto.Field( + proto.MESSAGE, + number=3, + message='AttributeValue', + ) + + operator: str = proto.Field( + proto.STRING, + number=1, + ) + input_args: MutableSequence[ArgumentDefinition] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=ArgumentDefinition, + ) + output_args: MutableSequence[ArgumentDefinition] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ArgumentDefinition, + ) + attributes: MutableSequence[AttributeDefinition] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=AttributeDefinition, + ) + resources: 'ResourceSpecification' = proto.Field( + proto.MESSAGE, + number=5, + message='ResourceSpecification', + ) + short_description: str = proto.Field( + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + + +class ResourceSpecification(proto.Message): + r"""ResourceSpec collects a set of resources that can + be used to specify requests and requirements. + + Note: Highly experimental as this can be runtime dependent. Can + use the "extras" field to experiment first before trying to + abstract it. + + Attributes: + cpu (str): + CPU specification. + + Examples: "100m", "0.5", "1", "2", ... correspond to 0.1, + half, 1, or 2 cpus. + + Leave empty to let the system decide. + + Note that this does *not* determine the cpu vender/make, or + its underlying clock speed and specific SIMD features. It is + only the amount time it requires in timeslicing. + cpu_limits (str): + CPU limit. + + Examples: + + "100m", "0.5", "1", "2", ... correspond to + 0.1, half, 1, or 2 cpus. + + Leave empty to indicate no limit. + memory (str): + Memory specification (in bytes). + + Examples: + + "128974848", "129e6", "129M", "123Mi", ... + correspond to 128974848 bytes, 129000000 bytes, + 129 mebibytes, 123 megabytes. + + Leave empty to let the system decide. + memory_limits (str): + Memory usage limits. + + Examples: + + "128974848", "129e6", "129M", "123Mi", ... + correspond to 128974848 bytes, 129000000 bytes, + 129 mebibytes, 123 megabytes. + + Leave empty to indicate no limit. + gpus (int): + Number of gpus. + latency_budget_ms (int): + The maximum latency that this operator may + use to process an element. + If non positive, then a system default will be + used. Operator developers should arrange for the + system compute resources to be aligned with this + latency budget; e.g. if you want a ML model to + produce results within 500ms, then you should + make sure you request enough cpu/gpu/memory to + achieve that. + """ + + cpu: str = proto.Field( + proto.STRING, + number=1, + ) + cpu_limits: str = proto.Field( + proto.STRING, + number=5, + ) + memory: str = proto.Field( + proto.STRING, + number=2, + ) + memory_limits: str = proto.Field( + proto.STRING, + number=6, + ) + gpus: int = proto.Field( + proto.INT32, + number=3, + ) + latency_budget_ms: int = proto.Field( + proto.INT32, + number=4, + ) + + +class AttributeValue(proto.Message): + r"""Represents an actual value of an operator attribute. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + i (int): + int. + + This field is a member of `oneof`_ ``value``. + f (float): + float. + + This field is a member of `oneof`_ ``value``. + b (bool): + bool. + + This field is a member of `oneof`_ ``value``. + s (bytes): + string. + + This field is a member of `oneof`_ ``value``. + """ + + i: int = proto.Field( + proto.INT64, + number=1, + oneof='value', + ) + f: float = proto.Field( + proto.FLOAT, + number=2, + oneof='value', + ) + b: bool = proto.Field( + proto.BOOL, + number=3, + oneof='value', + ) + s: bytes = proto.Field( + proto.BYTES, + number=4, + oneof='value', + ) + + +class AnalyzerDefinition(proto.Message): + r"""Defines an Analyzer. + + An analyzer processes data from its input streams using the + logic defined in the Operator that it represents. Of course, it + produces data for the output streams declared in the Operator. + + Attributes: + analyzer (str): + The name of this analyzer. + + Tentatively [a-z][a-z0-9]*(_[a-z0-9]+)*. + operator (str): + The name of the operator that this analyzer + runs. + Must match the name of a supported operator. + inputs (MutableSequence[google.cloud.visionai_v1.types.AnalyzerDefinition.StreamInput]): + Input streams. + attrs (MutableMapping[str, google.cloud.visionai_v1.types.AttributeValue]): + The attribute values that this analyzer + applies to the operator. + Supply a mapping between the attribute names and + the actual value you wish to apply. If an + attribute name is omitted, then it will take a + preconfigured default value. + debug_options (google.cloud.visionai_v1.types.AnalyzerDefinition.DebugOptions): + Debug options. + operator_option (google.cloud.visionai_v1.types.AnalyzerDefinition.OperatorOption): + Operator option. + """ + + class StreamInput(proto.Message): + r"""The inputs to this analyzer. + + We accept input name references of the following form: : + + Example: + + Suppose you had an operator named "SomeOp" that has 2 output + arguments, the first of which is named "foo" and the second of which + is named "bar", and an operator named "MyOp" that accepts 2 inputs. + + Also suppose that there is an analyzer named "some-analyzer" that is + running "SomeOp" and another analyzer named "my-analyzer" running + "MyOp". + + To indicate that "my-analyzer" is to consume "some-analyzer"'s "foo" + output as its first input and "some-analyzer"'s "bar" output as its + second input, you can set this field to the following: input = + ["some-analyzer:foo", "some-analyzer:bar"] + + Attributes: + input (str): + The name of the stream input (as discussed + above). + """ + + input: str = proto.Field( + proto.STRING, + number=1, + ) + + class DebugOptions(proto.Message): + r"""Options available for debugging purposes only. + + Attributes: + environment_variables (MutableMapping[str, str]): + Environment variables. + """ + + environment_variables: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + + class OperatorOption(proto.Message): + r"""Option related to the operator. + + Attributes: + tag (str): + Tag of the operator. + registry (str): + Registry of the operator. e.g. public, dev. + """ + + tag: str = proto.Field( + proto.STRING, + number=1, + ) + registry: str = proto.Field( + proto.STRING, + number=2, + ) + + analyzer: str = proto.Field( + proto.STRING, + number=1, + ) + operator: str = proto.Field( + proto.STRING, + number=2, + ) + inputs: MutableSequence[StreamInput] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=StreamInput, + ) + attrs: MutableMapping[str, 'AttributeValue'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message='AttributeValue', + ) + debug_options: DebugOptions = proto.Field( + proto.MESSAGE, + number=5, + message=DebugOptions, + ) + operator_option: OperatorOption = proto.Field( + proto.MESSAGE, + number=6, + message=OperatorOption, + ) + + +class AnalysisDefinition(proto.Message): + r"""Defines a full analysis. + + This is a description of the overall live analytics pipeline. + You may think of this as an edge list representation of a + multigraph. + + This may be directly authored by a human in protobuf textformat, + or it may be generated by a programming API (perhaps Python or + JavaScript depending on context). + + Attributes: + analyzers (MutableSequence[google.cloud.visionai_v1.types.AnalyzerDefinition]): + Analyzer definitions. + """ + + analyzers: MutableSequence['AnalyzerDefinition'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnalyzerDefinition', + ) + + +class RunStatus(proto.Message): + r"""Message describing the status of the Process. + + Attributes: + state (google.cloud.visionai_v1.types.RunStatus.State): + The state of the Process. + reason (str): + The reason of becoming the state. + """ + class State(proto.Enum): + r"""State represents the running status of the Process. + + Values: + STATE_UNSPECIFIED (0): + State is unspecified. + INITIALIZING (1): + INITIALIZING means the Process is scheduled + but yet ready to handle real traffic. + RUNNING (2): + RUNNING means the Process is up running and + handling traffic. + COMPLETED (3): + COMPLETED means the Process has completed the + processing, especially for non-streaming use + case. + FAILED (4): + FAILED means the Process failed to complete + the processing. + PENDING (5): + PENDING means the Process is created but yet + to be scheduled. + """ + STATE_UNSPECIFIED = 0 + INITIALIZING = 1 + RUNNING = 2 + COMPLETED = 3 + FAILED = 4 + PENDING = 5 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + reason: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva_resources.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva_resources.py new file mode 100644 index 000000000000..55f3306d0b00 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva_resources.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1.types import lva +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'Operator', + 'Analysis', + 'Process', + }, +) + + +class Operator(proto.Message): + r"""Message describing the Operator object. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + operator_definition (google.cloud.visionai_v1.types.OperatorDefinition): + The definition of the operator. + docker_image (str): + The link to the docker image of the operator. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + operator_definition: lva.OperatorDefinition = proto.Field( + proto.MESSAGE, + number=5, + message=lva.OperatorDefinition, + ) + docker_image: str = proto.Field( + proto.STRING, + number=6, + ) + + +class Analysis(proto.Message): + r"""Message describing the Analysis object. + + Attributes: + name (str): + The name of resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + analysis_definition (google.cloud.visionai_v1.types.AnalysisDefinition): + The definition of the analysis. + input_streams_mapping (MutableMapping[str, str]): + Map from the input parameter in the definition to the real + stream. E.g., suppose you had a stream source operator named + "input-0" and you try to receive from the real stream + "stream-0". You can add the following mapping: [input-0: + stream-0]. + output_streams_mapping (MutableMapping[str, str]): + Map from the output parameter in the definition to the real + stream. E.g., suppose you had a stream sink operator named + "output-0" and you try to send to the real stream + "stream-0". You can add the following mapping: [output-0: + stream-0]. + disable_event_watch (bool): + Boolean flag to indicate whether you would + like to disable the ability to automatically + start a Process when new event happening in the + input Stream. If you would like to start a + Process manually, the field needs to be set to + true. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + analysis_definition: lva.AnalysisDefinition = proto.Field( + proto.MESSAGE, + number=5, + message=lva.AnalysisDefinition, + ) + input_streams_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + output_streams_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + disable_event_watch: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class Process(proto.Message): + r"""Message describing the Process object. + + Attributes: + name (str): + The name of resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + analysis (str): + Required. Reference to an existing Analysis + resource. + attribute_overrides (MutableSequence[str]): + Optional. Attribute overrides of the Analyzers. Format for + each single override item: + "{analyzer_name}:{attribute_key}={value}". + run_status (google.cloud.visionai_v1.types.RunStatus): + Optional. Status of the Process. + run_mode (google.cloud.visionai_v1.types.RunMode): + Optional. Run mode of the Process. + event_id (str): + Optional. Event ID of the input/output + streams. This is useful when you have a + StreamSource/StreamSink operator in the + Analysis, and you want to manually specify the + Event to read from/write to. + batch_id (str): + Optional. Optional: Batch ID of the Process. + retry_count (int): + Optional. Optional: The number of retries for + a process in submission mode the system should + try before declaring failure. By default, no + retry will be performed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + analysis: str = proto.Field( + proto.STRING, + number=4, + ) + attribute_overrides: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + run_status: lva.RunStatus = proto.Field( + proto.MESSAGE, + number=6, + message=lva.RunStatus, + ) + run_mode: lva.RunMode = proto.Field( + proto.ENUM, + number=7, + enum=lva.RunMode, + ) + event_id: str = proto.Field( + proto.STRING, + number=8, + ) + batch_id: str = proto.Field( + proto.STRING, + number=9, + ) + retry_count: int = proto.Field( + proto.INT32, + number=10, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva_service.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva_service.py new file mode 100644 index 000000000000..1cdce8674b22 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/lva_service.py @@ -0,0 +1,969 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1.types import lva_resources +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'Registry', + 'ListOperatorsRequest', + 'ListOperatorsResponse', + 'GetOperatorRequest', + 'CreateOperatorRequest', + 'UpdateOperatorRequest', + 'DeleteOperatorRequest', + 'ListAnalysesRequest', + 'ListAnalysesResponse', + 'GetAnalysisRequest', + 'CreateAnalysisRequest', + 'UpdateAnalysisRequest', + 'DeleteAnalysisRequest', + 'ListProcessesRequest', + 'ListProcessesResponse', + 'GetProcessRequest', + 'CreateProcessRequest', + 'UpdateProcessRequest', + 'DeleteProcessRequest', + 'BatchRunProcessRequest', + 'BatchRunProcessResponse', + 'ResolveOperatorInfoRequest', + 'OperatorQuery', + 'ResolveOperatorInfoResponse', + 'ListPublicOperatorsRequest', + 'ListPublicOperatorsResponse', + }, +) + + +class Registry(proto.Enum): + r"""The enum of the types of the Registry. + + Values: + REGISTRY_UNSPECIFIED (0): + Registry is unspecified. + PUBLIC (1): + Public Registry containing the public + Operators released by Google. + PRIVATE (2): + Private Registry containing the local + registered operators. + """ + REGISTRY_UNSPECIFIED = 0 + PUBLIC = 1 + PRIVATE = 2 + + +class ListOperatorsRequest(proto.Message): + r"""Message for requesting list of Operators. + + Attributes: + parent (str): + Required. Parent value for + ListOperatorsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListOperatorsResponse(proto.Message): + r"""Message for response to listing Operators. + + Attributes: + operators (MutableSequence[google.cloud.visionai_v1.types.Operator]): + The list of Operator + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + operators: MutableSequence[lva_resources.Operator] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=lva_resources.Operator, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetOperatorRequest(proto.Message): + r"""Message for getting a Operator. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateOperatorRequest(proto.Message): + r"""Message for creating a Operator. + + Attributes: + parent (str): + Required. Value for parent. + operator_id (str): + Required. Id of the requesting object. + operator (google.cloud.visionai_v1.types.Operator): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + operator_id: str = proto.Field( + proto.STRING, + number=2, + ) + operator: lva_resources.Operator = proto.Field( + proto.MESSAGE, + number=3, + message=lva_resources.Operator, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateOperatorRequest(proto.Message): + r"""Message for updating a Operator. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Operator resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + operator (google.cloud.visionai_v1.types.Operator): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + operator: lva_resources.Operator = proto.Field( + proto.MESSAGE, + number=2, + message=lva_resources.Operator, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteOperatorRequest(proto.Message): + r"""Message for deleting a Operator + + Attributes: + name (str): + Required. Name of the resource + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAnalysesRequest(proto.Message): + r"""Message for requesting list of Analyses + + Attributes: + parent (str): + Required. Parent value for + ListAnalysesRequest + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAnalysesResponse(proto.Message): + r"""Message for response to listing Analyses + + Attributes: + analyses (MutableSequence[google.cloud.visionai_v1.types.Analysis]): + The list of Analysis + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + analyses: MutableSequence[lva_resources.Analysis] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=lva_resources.Analysis, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetAnalysisRequest(proto.Message): + r"""Message for getting an Analysis. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAnalysisRequest(proto.Message): + r"""Message for creating an Analysis. + + Attributes: + parent (str): + Required. Value for parent. + analysis_id (str): + Required. Id of the requesting object. + analysis (google.cloud.visionai_v1.types.Analysis): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + analysis_id: str = proto.Field( + proto.STRING, + number=2, + ) + analysis: lva_resources.Analysis = proto.Field( + proto.MESSAGE, + number=3, + message=lva_resources.Analysis, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateAnalysisRequest(proto.Message): + r"""Message for updating an Analysis. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Analysis resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + analysis (google.cloud.visionai_v1.types.Analysis): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + analysis: lva_resources.Analysis = proto.Field( + proto.MESSAGE, + number=2, + message=lva_resources.Analysis, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteAnalysisRequest(proto.Message): + r"""Message for deleting an Analysis. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListProcessesRequest(proto.Message): + r"""Message for requesting list of Processes. + + Attributes: + parent (str): + Required. Parent value for + ListProcessesRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListProcessesResponse(proto.Message): + r"""Message for response to listing Processes. + + Attributes: + processes (MutableSequence[google.cloud.visionai_v1.types.Process]): + The list of Processes. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + processes: MutableSequence[lva_resources.Process] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=lva_resources.Process, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetProcessRequest(proto.Message): + r"""Message for getting a Process. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateProcessRequest(proto.Message): + r"""Message for creating a Process. + + Attributes: + parent (str): + Required. Value for parent. + process_id (str): + Required. Id of the requesting object. + process (google.cloud.visionai_v1.types.Process): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + process_id: str = proto.Field( + proto.STRING, + number=2, + ) + process: lva_resources.Process = proto.Field( + proto.MESSAGE, + number=3, + message=lva_resources.Process, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateProcessRequest(proto.Message): + r"""Message for updating a Process. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Process resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + process (google.cloud.visionai_v1.types.Process): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + process: lva_resources.Process = proto.Field( + proto.MESSAGE, + number=2, + message=lva_resources.Process, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteProcessRequest(proto.Message): + r"""Message for deleting a Process. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchRunProcessRequest(proto.Message): + r"""Request message for running the processes in a batch. + + Attributes: + parent (str): + Required. The parent resource shared by all + processes being created. + requests (MutableSequence[google.cloud.visionai_v1.types.CreateProcessRequest]): + Required. The create process requests. + options (google.cloud.visionai_v1.types.BatchRunProcessRequest.BatchRunProcessOptions): + Optional. Options for batch processes. + batch_id (str): + Output only. The batch ID. + """ + + class BatchRunProcessOptions(proto.Message): + r"""Options for batch processes. + + Attributes: + retry_count (int): + The retry counts per process. Default: 3. + batch_size (int): + The batch size. Default: 5, maximum: 100. + """ + + retry_count: int = proto.Field( + proto.INT32, + number=1, + ) + batch_size: int = proto.Field( + proto.INT32, + number=2, + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['CreateProcessRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='CreateProcessRequest', + ) + options: BatchRunProcessOptions = proto.Field( + proto.MESSAGE, + number=3, + message=BatchRunProcessOptions, + ) + batch_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class BatchRunProcessResponse(proto.Message): + r"""Response message for running the processes in a batch. + + Attributes: + batch_id (str): + The batch ID. + processes (MutableSequence[google.cloud.visionai_v1.types.Process]): + Processes created. + """ + + batch_id: str = proto.Field( + proto.STRING, + number=1, + ) + processes: MutableSequence[lva_resources.Process] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=lva_resources.Process, + ) + + +class ResolveOperatorInfoRequest(proto.Message): + r"""Request message for querying operator info. + + Attributes: + parent (str): + Required. Parent value for + ResolveOperatorInfoRequest. + queries (MutableSequence[google.cloud.visionai_v1.types.OperatorQuery]): + Required. The operator queries. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + queries: MutableSequence['OperatorQuery'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OperatorQuery', + ) + + +class OperatorQuery(proto.Message): + r"""OperatorQuery represents one query to a Operator. + + Attributes: + operator (str): + Required. The canonical Name of the operator. + e.g. OccupancyCounting. + tag (str): + Optional. Tag of the operator. + registry (google.cloud.visionai_v1.types.Registry): + Optional. Registry of the operator. + """ + + operator: str = proto.Field( + proto.STRING, + number=1, + ) + tag: str = proto.Field( + proto.STRING, + number=2, + ) + registry: 'Registry' = proto.Field( + proto.ENUM, + number=3, + enum='Registry', + ) + + +class ResolveOperatorInfoResponse(proto.Message): + r"""Response message of ResolveOperatorInfo API. + + Attributes: + operators (MutableSequence[google.cloud.visionai_v1.types.Operator]): + Operators with detailed information. + """ + + operators: MutableSequence[lva_resources.Operator] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=lva_resources.Operator, + ) + + +class ListPublicOperatorsRequest(proto.Message): + r"""Request message of ListPublicOperatorsRequest API. + + Attributes: + parent (str): + Required. Parent value for + ListPublicOperatorsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListPublicOperatorsResponse(proto.Message): + r"""Response message of ListPublicOperators API. + + Attributes: + operators (MutableSequence[google.cloud.visionai_v1.types.Operator]): + The list of Operator + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + operators: MutableSequence[lva_resources.Operator] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=lva_resources.Operator, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/platform.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/platform.py new file mode 100644 index 000000000000..01fb6c7877dd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/platform.py @@ -0,0 +1,3745 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1.types import annotations as gcv_annotations +from google.cloud.visionai_v1.types import common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'ModelType', + 'AcceleratorType', + 'DataType', + 'DeleteApplicationInstancesResponse', + 'CreateApplicationInstancesResponse', + 'UpdateApplicationInstancesResponse', + 'CreateApplicationInstancesRequest', + 'DeleteApplicationInstancesRequest', + 'DeployApplicationResponse', + 'UndeployApplicationResponse', + 'RemoveApplicationStreamInputResponse', + 'AddApplicationStreamInputResponse', + 'UpdateApplicationStreamInputResponse', + 'ListApplicationsRequest', + 'ListApplicationsResponse', + 'GetApplicationRequest', + 'CreateApplicationRequest', + 'UpdateApplicationRequest', + 'DeleteApplicationRequest', + 'DeployApplicationRequest', + 'UndeployApplicationRequest', + 'ApplicationStreamInput', + 'AddApplicationStreamInputRequest', + 'UpdateApplicationStreamInputRequest', + 'RemoveApplicationStreamInputRequest', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'GetInstanceRequest', + 'ListDraftsRequest', + 'ListDraftsResponse', + 'GetDraftRequest', + 'CreateDraftRequest', + 'UpdateDraftRequest', + 'UpdateApplicationInstancesRequest', + 'DeleteDraftRequest', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListPrebuiltProcessorsRequest', + 'ListPrebuiltProcessorsResponse', + 'GetProcessorRequest', + 'CreateProcessorRequest', + 'UpdateProcessorRequest', + 'DeleteProcessorRequest', + 'Application', + 'ApplicationConfigs', + 'Node', + 'Draft', + 'Instance', + 'ApplicationInstance', + 'Processor', + 'ProcessorIOSpec', + 'CustomProcessorSourceInfo', + 'ProcessorConfig', + 'StreamWithAnnotation', + 'ApplicationNodeAnnotation', + 'ResourceAnnotations', + 'VideoStreamInputConfig', + 'AIEnabledDevicesInputConfig', + 'MediaWarehouseConfig', + 'PersonBlurConfig', + 'OccupancyCountConfig', + 'PersonVehicleDetectionConfig', + 'PersonalProtectiveEquipmentDetectionConfig', + 'GeneralObjectDetectionConfig', + 'BigQueryConfig', + 'VertexAutoMLVisionConfig', + 'VertexAutoMLVideoConfig', + 'VertexCustomConfig', + 'GcsOutputConfig', + 'UniversalInputConfig', + 'MachineSpec', + 'AutoscalingMetricSpec', + 'DedicatedResources', + 'ProductRecognizerConfig', + 'TagRecognizerConfig', + 'TagParsingConfig', + }, +) + + +class ModelType(proto.Enum): + r"""All the supported model types in Vision AI App Platform. + + Values: + MODEL_TYPE_UNSPECIFIED (0): + Processor Type UNSPECIFIED. + IMAGE_CLASSIFICATION (1): + Model Type Image Classification. + OBJECT_DETECTION (2): + Model Type Object Detection. + VIDEO_CLASSIFICATION (3): + Model Type Video Classification. + VIDEO_OBJECT_TRACKING (4): + Model Type Object Tracking. + VIDEO_ACTION_RECOGNITION (5): + Model Type Action Recognition. + OCCUPANCY_COUNTING (6): + Model Type Occupancy Counting. + PERSON_BLUR (7): + Model Type Person Blur. + VERTEX_CUSTOM (8): + Model Type Vertex Custom. + PRODUCT_RECOGNIZER (9): + Model Type Product Recognizer. + TAG_RECOGNIZER (10): + Model Type Tag Recognizer. + SYNTH_ID (15): + Model Type SynthID. + """ + MODEL_TYPE_UNSPECIFIED = 0 + IMAGE_CLASSIFICATION = 1 + OBJECT_DETECTION = 2 + VIDEO_CLASSIFICATION = 3 + VIDEO_OBJECT_TRACKING = 4 + VIDEO_ACTION_RECOGNITION = 5 + OCCUPANCY_COUNTING = 6 + PERSON_BLUR = 7 + VERTEX_CUSTOM = 8 + PRODUCT_RECOGNIZER = 9 + TAG_RECOGNIZER = 10 + SYNTH_ID = 15 + + +class AcceleratorType(proto.Enum): + r"""Represents a hardware accelerator type. + + Values: + ACCELERATOR_TYPE_UNSPECIFIED (0): + Unspecified accelerator type, which means no + accelerator. + NVIDIA_TESLA_K80 (1): + Nvidia Tesla K80 GPU. + NVIDIA_TESLA_P100 (2): + Nvidia Tesla P100 GPU. + NVIDIA_TESLA_V100 (3): + Nvidia Tesla V100 GPU. + NVIDIA_TESLA_P4 (4): + Nvidia Tesla P4 GPU. + NVIDIA_TESLA_T4 (5): + Nvidia Tesla T4 GPU. + NVIDIA_TESLA_A100 (8): + Nvidia Tesla A100 GPU. + TPU_V2 (6): + TPU v2. + TPU_V3 (7): + TPU v3. + """ + ACCELERATOR_TYPE_UNSPECIFIED = 0 + NVIDIA_TESLA_K80 = 1 + NVIDIA_TESLA_P100 = 2 + NVIDIA_TESLA_V100 = 3 + NVIDIA_TESLA_P4 = 4 + NVIDIA_TESLA_T4 = 5 + NVIDIA_TESLA_A100 = 8 + TPU_V2 = 6 + TPU_V3 = 7 + + +class DataType(proto.Enum): + r"""All supported data types. + + Values: + DATA_TYPE_UNSPECIFIED (0): + The default value of DataType. + VIDEO (1): + Video data type like H264. + IMAGE (3): + Image data type. + PROTO (2): + Protobuf data type, usually used for general + data blob. + PLACEHOLDER (4): + A placeholder data type, applicable for the universal input + processor which supports any data type. This will be + instantiated and replaced by a concrete underlying + ``DataType`` during instance deployment. + """ + DATA_TYPE_UNSPECIFIED = 0 + VIDEO = 1 + IMAGE = 3 + PROTO = 2 + PLACEHOLDER = 4 + + +class DeleteApplicationInstancesResponse(proto.Message): + r"""Message for DeleteApplicationInstance Response. + """ + + +class CreateApplicationInstancesResponse(proto.Message): + r"""Message for CreateApplicationInstance Response. + """ + + +class UpdateApplicationInstancesResponse(proto.Message): + r"""Message for UpdateApplicationInstances Response. + """ + + +class CreateApplicationInstancesRequest(proto.Message): + r"""Message for adding stream input to an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_instances (MutableSequence[google.cloud.visionai_v1.types.ApplicationInstance]): + Required. The resources being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_instances: MutableSequence['ApplicationInstance'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationInstance', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteApplicationInstancesRequest(proto.Message): + r"""Message for removing stream input from an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + instance_ids (MutableSequence[str]): + Required. Id of the requesting object. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + instance_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeployApplicationResponse(proto.Message): + r"""RPC Request Messages. + Message for DeployApplication Response. + + """ + + +class UndeployApplicationResponse(proto.Message): + r"""Message for UndeployApplication Response. + """ + + +class RemoveApplicationStreamInputResponse(proto.Message): + r"""Message for RemoveApplicationStreamInput Response. + """ + + +class AddApplicationStreamInputResponse(proto.Message): + r"""Message for AddApplicationStreamInput Response. + """ + + +class UpdateApplicationStreamInputResponse(proto.Message): + r"""Message for AddApplicationStreamInput Response. + """ + + +class ListApplicationsRequest(proto.Message): + r"""Message for requesting list of Applications. + + Attributes: + parent (str): + Required. Parent value for + ListApplicationsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListApplicationsResponse(proto.Message): + r"""Message for response to listing Applications. + + Attributes: + applications (MutableSequence[google.cloud.visionai_v1.types.Application]): + The list of Application. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + applications: MutableSequence['Application'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Application', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetApplicationRequest(proto.Message): + r"""Message for getting a Application. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateApplicationRequest(proto.Message): + r"""Message for creating a Application. + + Attributes: + parent (str): + Required. Value for parent. + application_id (str): + Required. Id of the requesting object. + application (google.cloud.visionai_v1.types.Application): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + application_id: str = proto.Field( + proto.STRING, + number=2, + ) + application: 'Application' = proto.Field( + proto.MESSAGE, + number=3, + message='Application', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateApplicationRequest(proto.Message): + r"""Message for updating an Application. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Application resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + application (google.cloud.visionai_v1.types.Application): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + application: 'Application' = proto.Field( + proto.MESSAGE, + number=2, + message='Application', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteApplicationRequest(proto.Message): + r"""Message for deleting an Application. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + force (bool): + Optional. If set to true, any instances and + drafts from this application will also be + deleted. (Otherwise, the request will only work + if the application has no instances and drafts.) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeployApplicationRequest(proto.Message): + r"""Message for deploying an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + validate_only (bool): + If set, validate the request and preview the + application graph, but do not actually deploy + it. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + enable_monitoring (bool): + Optional. Whether or not to enable monitoring + for the application on deployment. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + enable_monitoring: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UndeployApplicationRequest(proto.Message): + r"""Message for undeploying an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ApplicationStreamInput(proto.Message): + r"""Message about a single stream input config. + + Attributes: + stream_with_annotation (google.cloud.visionai_v1.types.StreamWithAnnotation): + + """ + + stream_with_annotation: 'StreamWithAnnotation' = proto.Field( + proto.MESSAGE, + number=1, + message='StreamWithAnnotation', + ) + + +class AddApplicationStreamInputRequest(proto.Message): + r"""Message for adding stream input to an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_stream_inputs (MutableSequence[google.cloud.visionai_v1.types.ApplicationStreamInput]): + The stream inputs to add, the stream resource + name is the key of each StreamInput, and it must + be unique within each application. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_stream_inputs: MutableSequence['ApplicationStreamInput'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationStreamInput', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateApplicationStreamInputRequest(proto.Message): + r"""Message for updating stream input to an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_stream_inputs (MutableSequence[google.cloud.visionai_v1.types.ApplicationStreamInput]): + The stream inputs to update, the stream + resource name is the key of each StreamInput, + and it must be unique within each application. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + allow_missing (bool): + If true, UpdateApplicationStreamInput will + insert stream input to application even if the + target stream is not included in the + application. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_stream_inputs: MutableSequence['ApplicationStreamInput'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationStreamInput', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RemoveApplicationStreamInputRequest(proto.Message): + r"""Message for removing stream input from an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + target_stream_inputs (MutableSequence[google.cloud.visionai_v1.types.RemoveApplicationStreamInputRequest.TargetStreamInput]): + The target stream to remove. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + class TargetStreamInput(proto.Message): + r"""Message about target streamInput to remove. + + Attributes: + stream (str): + + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + target_stream_inputs: MutableSequence[TargetStreamInput] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=TargetStreamInput, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListInstancesRequest(proto.Message): + r"""Message for requesting list of Instances. + + Attributes: + parent (str): + Required. Parent value for + ListInstancesRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInstancesResponse(proto.Message): + r"""Message for response to listing Instances. + + Attributes: + instances (MutableSequence[google.cloud.visionai_v1.types.Instance]): + The list of Instance. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence['Instance'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Instance', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetInstanceRequest(proto.Message): + r"""Message for getting a Instance. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDraftsRequest(proto.Message): + r"""Message for requesting list of Drafts. + + Attributes: + parent (str): + Required. Parent value for ListDraftsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListDraftsResponse(proto.Message): + r"""Message for response to listing Drafts. + + Attributes: + drafts (MutableSequence[google.cloud.visionai_v1.types.Draft]): + The list of Draft. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + drafts: MutableSequence['Draft'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Draft', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetDraftRequest(proto.Message): + r"""Message for getting a Draft. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDraftRequest(proto.Message): + r"""Message for creating a Draft. + + Attributes: + parent (str): + Required. Value for parent. + draft_id (str): + Required. Id of the requesting object. + draft (google.cloud.visionai_v1.types.Draft): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + draft_id: str = proto.Field( + proto.STRING, + number=2, + ) + draft: 'Draft' = proto.Field( + proto.MESSAGE, + number=3, + message='Draft', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateDraftRequest(proto.Message): + r"""Message for updating a Draft. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + draft (google.cloud.visionai_v1.types.Draft): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + allow_missing (bool): + If true, UpdateDraftRequest will create one resource if the + target resource doesn't exist, this time, the field_mask + will be ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + draft: 'Draft' = proto.Field( + proto.MESSAGE, + number=2, + message='Draft', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateApplicationInstancesRequest(proto.Message): + r"""Message for updating an ApplicationInstance. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_instances (MutableSequence[google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]): + + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + allow_missing (bool): + If true, Update Request will create one resource if the + target resource doesn't exist, this time, the field_mask + will be ignored. + """ + + class UpdateApplicationInstance(proto.Message): + r""" + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + instance (google.cloud.visionai_v1.types.Instance): + Required. The resource being updated. + instance_id (str): + Required. The id of the instance. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + instance: 'Instance' = proto.Field( + proto.MESSAGE, + number=2, + message='Instance', + ) + instance_id: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_instances: MutableSequence[UpdateApplicationInstance] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=UpdateApplicationInstance, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteDraftRequest(proto.Message): + r"""Message for deleting a Draft. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListProcessorsRequest(proto.Message): + r"""Message for requesting list of Processors. + + Attributes: + parent (str): + Required. Parent value for + ListProcessorsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListProcessorsResponse(proto.Message): + r"""Message for response to listing Processors. + + Attributes: + processors (MutableSequence[google.cloud.visionai_v1.types.Processor]): + The list of Processor. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + processors: MutableSequence['Processor'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Processor', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListPrebuiltProcessorsRequest(proto.Message): + r"""Request Message for listing Prebuilt Processors. + + Attributes: + parent (str): + Required. Parent path. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPrebuiltProcessorsResponse(proto.Message): + r"""Response Message for listing Prebuilt Processors. + + Attributes: + processors (MutableSequence[google.cloud.visionai_v1.types.Processor]): + The list of Processor. + """ + + processors: MutableSequence['Processor'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Processor', + ) + + +class GetProcessorRequest(proto.Message): + r"""Message for getting a Processor. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateProcessorRequest(proto.Message): + r"""Message for creating a Processor. + + Attributes: + parent (str): + Required. Value for parent. + processor_id (str): + Required. Id of the requesting object. + processor (google.cloud.visionai_v1.types.Processor): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + processor_id: str = proto.Field( + proto.STRING, + number=2, + ) + processor: 'Processor' = proto.Field( + proto.MESSAGE, + number=3, + message='Processor', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateProcessorRequest(proto.Message): + r"""Message for updating a Processor. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Processor resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + processor (google.cloud.visionai_v1.types.Processor): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + processor: 'Processor' = proto.Field( + proto.MESSAGE, + number=2, + message='Processor', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteProcessorRequest(proto.Message): + r"""Message for deleting a Processor. + + Attributes: + name (str): + Required. Name of the resource + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Application(proto.Message): + r"""Message describing Application object + + Attributes: + name (str): + name of resource + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update timestamp + labels (MutableMapping[str, str]): + Labels as key value pairs + display_name (str): + Required. A user friendly display name for + the solution. + description (str): + A description for this application. + application_configs (google.cloud.visionai_v1.types.ApplicationConfigs): + Application graph configuration. + runtime_info (google.cloud.visionai_v1.types.Application.ApplicationRuntimeInfo): + Output only. Application graph runtime info. + Only exists when application state equals to + DEPLOYED. + state (google.cloud.visionai_v1.types.Application.State): + Output only. State of the application. + billing_mode (google.cloud.visionai_v1.types.Application.BillingMode): + Billing mode of the application. + """ + class State(proto.Enum): + r"""State of the Application + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + CREATED (1): + State CREATED. + DEPLOYING (2): + State DEPLOYING. + DEPLOYED (3): + State DEPLOYED. + UNDEPLOYING (4): + State UNDEPLOYING. + DELETED (5): + State DELETED. + ERROR (6): + State ERROR. + CREATING (7): + State CREATING. + UPDATING (8): + State Updating. + DELETING (9): + State Deleting. + FIXING (10): + State Fixing. + """ + STATE_UNSPECIFIED = 0 + CREATED = 1 + DEPLOYING = 2 + DEPLOYED = 3 + UNDEPLOYING = 4 + DELETED = 5 + ERROR = 6 + CREATING = 7 + UPDATING = 8 + DELETING = 9 + FIXING = 10 + + class BillingMode(proto.Enum): + r"""Billing mode of the Application + + Values: + BILLING_MODE_UNSPECIFIED (0): + The default value. + PAYG (1): + Pay as you go billing mode. + MONTHLY (2): + Monthly billing mode. + """ + BILLING_MODE_UNSPECIFIED = 0 + PAYG = 1 + MONTHLY = 2 + + class ApplicationRuntimeInfo(proto.Message): + r"""Message storing the runtime information of the application. + + Attributes: + deploy_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the engine be deployed + global_output_resources (MutableSequence[google.cloud.visionai_v1.types.Application.ApplicationRuntimeInfo.GlobalOutputResource]): + Globally created resources like warehouse + dataschemas. + monitoring_config (google.cloud.visionai_v1.types.Application.ApplicationRuntimeInfo.MonitoringConfig): + Monitoring-related configuration for this + application. + """ + + class GlobalOutputResource(proto.Message): + r"""Message about output resources from application. + + Attributes: + output_resource (str): + The full resource name of the outputted + resources. + producer_node (str): + The name of graph node who produces the output resource + name. For example: output_resource: + /projects/123/locations/us-central1/corpora/my-corpus/dataSchemas/my-schema + producer_node: occupancy-count + key (str): + The key of the output resource, it has to be + unique within the same producer node. One + producer node can output several output + resources, the key can be used to match + corresponding output resources. + """ + + output_resource: str = proto.Field( + proto.STRING, + number=1, + ) + producer_node: str = proto.Field( + proto.STRING, + number=2, + ) + key: str = proto.Field( + proto.STRING, + number=3, + ) + + class MonitoringConfig(proto.Message): + r"""Monitoring-related configuration for an application. + + Attributes: + enabled (bool): + Whether this application has monitoring + enabled. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + deploy_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + global_output_resources: MutableSequence['Application.ApplicationRuntimeInfo.GlobalOutputResource'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Application.ApplicationRuntimeInfo.GlobalOutputResource', + ) + monitoring_config: 'Application.ApplicationRuntimeInfo.MonitoringConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='Application.ApplicationRuntimeInfo.MonitoringConfig', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + application_configs: 'ApplicationConfigs' = proto.Field( + proto.MESSAGE, + number=7, + message='ApplicationConfigs', + ) + runtime_info: ApplicationRuntimeInfo = proto.Field( + proto.MESSAGE, + number=8, + message=ApplicationRuntimeInfo, + ) + state: State = proto.Field( + proto.ENUM, + number=9, + enum=State, + ) + billing_mode: BillingMode = proto.Field( + proto.ENUM, + number=12, + enum=BillingMode, + ) + + +class ApplicationConfigs(proto.Message): + r"""Message storing the graph of the application. + + Attributes: + nodes (MutableSequence[google.cloud.visionai_v1.types.Node]): + A list of nodes in the application graph. + event_delivery_config (google.cloud.visionai_v1.types.ApplicationConfigs.EventDeliveryConfig): + Event-related configuration for this + application. + """ + + class EventDeliveryConfig(proto.Message): + r"""message storing the config for event delivery + + Attributes: + channel (str): + The delivery channel for the event notification, only + pub/sub topic is supported now. Example channel: + [//pubsub.googleapis.com/projects/visionai-testing-stable/topics/test-topic] + minimal_delivery_interval (google.protobuf.duration_pb2.Duration): + The expected delivery interval for the same event. The same + event won't be notified multiple times during this internal + event that it is happening multiple times during the period + of time.The same event is identified by . + """ + + channel: str = proto.Field( + proto.STRING, + number=1, + ) + minimal_delivery_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + nodes: MutableSequence['Node'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Node', + ) + event_delivery_config: EventDeliveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=EventDeliveryConfig, + ) + + +class Node(proto.Message): + r"""Message describing node object. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + output_all_output_channels_to_stream (bool): + By default, the output of the node will only be available to + downstream nodes. To consume the direct output from the + application node, the output must be sent to Vision AI + Streams at first. + + By setting output_all_output_channels_to_stream to true, App + Platform will automatically send all the outputs of the + current node to Vision AI Stream resources (one stream per + output channel). The output stream resource will be created + by App Platform automatically during deployment and deleted + after application un-deployment. Note that this config + applies to all the Application Instances. + + The output stream can be override at instance level by + configuring the ``output_resources`` section of Instance + resource. ``producer_node`` should be current node, + ``output_resource_binding`` should be the output channel + name (or leave it blank if there is only 1 output channel of + the processor) and ``output_resource`` should be the target + output stream. + + This field is a member of `oneof`_ ``stream_output_config``. + name (str): + Required. A unique name for the node. + display_name (str): + A user friendly display name for the node. + node_config (google.cloud.visionai_v1.types.ProcessorConfig): + Node config. + processor (str): + Processor name refer to the chosen processor + resource. + parents (MutableSequence[google.cloud.visionai_v1.types.Node.InputEdge]): + Parent node. Input node should not have + parent node. For V1 Alpha1/Beta only media + warehouse node can have multiple parents, other + types of nodes will only have one parent. + """ + + class InputEdge(proto.Message): + r"""Message describing one edge pointing into a node. + + Attributes: + parent_node (str): + The name of the parent node. + parent_output_channel (str): + The connected output artifact of the parent + node. It can be omitted if target processor only + has 1 output artifact. + connected_input_channel (str): + The connected input channel of the current + node's processor. It can be omitted if target + processor only has 1 input channel. + """ + + parent_node: str = proto.Field( + proto.STRING, + number=1, + ) + parent_output_channel: str = proto.Field( + proto.STRING, + number=2, + ) + connected_input_channel: str = proto.Field( + proto.STRING, + number=3, + ) + + output_all_output_channels_to_stream: bool = proto.Field( + proto.BOOL, + number=6, + oneof='stream_output_config', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + node_config: 'ProcessorConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='ProcessorConfig', + ) + processor: str = proto.Field( + proto.STRING, + number=4, + ) + parents: MutableSequence[InputEdge] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=InputEdge, + ) + + +class Draft(proto.Message): + r"""Message describing Draft object + + Attributes: + name (str): + name of resource + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + labels (MutableMapping[str, str]): + Labels as key value pairs + display_name (str): + Required. A user friendly display name for + the solution. + description (str): + A description for this application. + draft_application_configs (google.cloud.visionai_v1.types.ApplicationConfigs): + The draft application configs which haven't + been updated to an application. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + draft_application_configs: 'ApplicationConfigs' = proto.Field( + proto.MESSAGE, + number=6, + message='ApplicationConfigs', + ) + + +class Instance(proto.Message): + r"""Message describing Instance object + Next ID: 12 + + Attributes: + name (str): + Output only. name of resource + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update timestamp + labels (MutableMapping[str, str]): + Labels as key value pairs + display_name (str): + Required. A user friendly display name for + the solution. + description (str): + A description for this instance. + instance_type (google.cloud.visionai_v1.types.Instance.InstanceType): + The instance type for the current instance. + input_resources (MutableSequence[google.cloud.visionai_v1.types.Instance.InputResource]): + The input resources for the current application instance. + For example: input_resources: + visionai.googleapis.com/v1/projects/123/locations/us-central1/clusters/456/streams/stream-a + output_resources (MutableSequence[google.cloud.visionai_v1.types.Instance.OutputResource]): + All the output resources associated to one + application instance. + state (google.cloud.visionai_v1.types.Instance.State): + State of the instance. + """ + class InstanceType(proto.Enum): + r"""All the supported instance types. + + Values: + INSTANCE_TYPE_UNSPECIFIED (0): + Unspecified instance type. If the instance type is not + specified, the default one is STREAMING_PREDICTION. + STREAMING_PREDICTION (1): + Instance type for streaming prediction. + BATCH_PREDICTION (2): + Instance type for batch prediction. + ONLINE_PREDICTION (3): + Instance type for online prediction. + """ + INSTANCE_TYPE_UNSPECIFIED = 0 + STREAMING_PREDICTION = 1 + BATCH_PREDICTION = 2 + ONLINE_PREDICTION = 3 + + class State(proto.Enum): + r"""State of the Instance + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + CREATING (1): + State CREATING. + CREATED (2): + State CREATED. + DEPLOYING (3): + State DEPLOYING. + DEPLOYED (4): + State DEPLOYED. + UNDEPLOYING (5): + State UNDEPLOYING. + DELETED (6): + State DELETED. + ERROR (7): + State ERROR. + UPDATING (8): + State Updating + DELETING (9): + State Deleting. + FIXING (10): + State Fixing. + FINISHED (11): + State Finished. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + CREATED = 2 + DEPLOYING = 3 + DEPLOYED = 4 + UNDEPLOYING = 5 + DELETED = 6 + ERROR = 7 + UPDATING = 8 + DELETING = 9 + FIXING = 10 + FINISHED = 11 + + class InputResource(proto.Message): + r"""Message of input resource used in one application instance. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + input_resource (str): + The direct input resource name. If the instance type is + STREAMING_PREDICTION, the input resource is in format of + "projects/123/locations/us-central1/clusters/456/streams/stream-a". + If the instance type is BATCH_PREDICTION from Cloud Storage + input container, the input resource is in format of + "gs://bucket-a". + + This field is a member of `oneof`_ ``input_resource_information``. + annotated_stream (google.cloud.visionai_v1.types.StreamWithAnnotation): + If the input resource is VisionAI Stream, the associated + annotations can be specified using annotated_stream instead. + + This field is a member of `oneof`_ ``input_resource_information``. + data_type (google.cloud.visionai_v1.types.DataType): + Data type for the current input resource. + consumer_node (str): + The name of graph node who receives the input resource. For + example: input_resource: + visionai.googleapis.com/v1/projects/123/locations/us-central1/clusters/456/streams/input-stream-a + consumer_node: stream-input + input_resource_binding (str): + The specific input resource binding which + will consume the current Input Resource, can be + ignored is there is only 1 input binding. + annotations (google.cloud.visionai_v1.types.ResourceAnnotations): + Contains resource annotations. + """ + + input_resource: str = proto.Field( + proto.STRING, + number=1, + oneof='input_resource_information', + ) + annotated_stream: 'StreamWithAnnotation' = proto.Field( + proto.MESSAGE, + number=4, + oneof='input_resource_information', + message='StreamWithAnnotation', + ) + data_type: 'DataType' = proto.Field( + proto.ENUM, + number=6, + enum='DataType', + ) + consumer_node: str = proto.Field( + proto.STRING, + number=2, + ) + input_resource_binding: str = proto.Field( + proto.STRING, + number=3, + ) + annotations: 'ResourceAnnotations' = proto.Field( + proto.MESSAGE, + number=5, + message='ResourceAnnotations', + ) + + class OutputResource(proto.Message): + r"""Message of output resource used in one application instance. + + Attributes: + output_resource (str): + The output resource name for the current + application instance. + producer_node (str): + The name of graph node who produces the output resource + name. For example: output_resource: + /projects/123/locations/us-central1/clusters/456/streams/output-application-789-stream-a-occupancy-counting + producer_node: occupancy-counting + output_resource_binding (str): + The specific output resource binding which + produces the current OutputResource. + is_temporary (bool): + Output only. Whether the output resource is + temporary which means the resource is generated + during the deployment of the application. + Temporary resource will be deleted during the + undeployment of the application. + autogen (bool): + Output only. Whether the output resource is + created automatically by the Vision AI App + Platform. + """ + + output_resource: str = proto.Field( + proto.STRING, + number=1, + ) + producer_node: str = proto.Field( + proto.STRING, + number=2, + ) + output_resource_binding: str = proto.Field( + proto.STRING, + number=4, + ) + is_temporary: bool = proto.Field( + proto.BOOL, + number=3, + ) + autogen: bool = proto.Field( + proto.BOOL, + number=5, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + instance_type: InstanceType = proto.Field( + proto.ENUM, + number=10, + enum=InstanceType, + ) + input_resources: MutableSequence[InputResource] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=InputResource, + ) + output_resources: MutableSequence[OutputResource] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=OutputResource, + ) + state: State = proto.Field( + proto.ENUM, + number=9, + enum=State, + ) + + +class ApplicationInstance(proto.Message): + r"""Message for creating a Instance. + + Attributes: + instance_id (str): + Required. Id of the requesting object. + instance (google.cloud.visionai_v1.types.Instance): + Required. The resource being created. + """ + + instance_id: str = proto.Field( + proto.STRING, + number=1, + ) + instance: 'Instance' = proto.Field( + proto.MESSAGE, + number=2, + message='Instance', + ) + + +class Processor(proto.Message): + r"""Message describing Processor object. + Next ID: 19 + + Attributes: + name (str): + name of resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + display_name (str): + Required. A user friendly display name for + the processor. + description (str): + Illustrative sentences for describing the + functionality of the processor. + processor_type (google.cloud.visionai_v1.types.Processor.ProcessorType): + Output only. Processor Type. + model_type (google.cloud.visionai_v1.types.ModelType): + Model Type. + custom_processor_source_info (google.cloud.visionai_v1.types.CustomProcessorSourceInfo): + Source info for customer created processor. + state (google.cloud.visionai_v1.types.Processor.ProcessorState): + Output only. State of the Processor. + processor_io_spec (google.cloud.visionai_v1.types.ProcessorIOSpec): + Output only. [Output only] The input / output specifications + of a processor, each type of processor has fixed input / + output specs which cannot be altered by customer. + configuration_typeurl (str): + Output only. The corresponding configuration + can be used in the Application to customize the + behavior of the processor. + supported_annotation_types (MutableSequence[google.cloud.visionai_v1.types.StreamAnnotationType]): + + supports_post_processing (bool): + Indicates if the processor supports post + processing. + supported_instance_types (MutableSequence[google.cloud.visionai_v1.types.Instance.InstanceType]): + Which instance types this processor supports; if empty, this + default to STREAMING_PREDICTION. + """ + class ProcessorType(proto.Enum): + r"""Type + + Values: + PROCESSOR_TYPE_UNSPECIFIED (0): + Processor Type UNSPECIFIED. + PRETRAINED (1): + Processor Type PRETRAINED. + Pretrained processor is developed by Vision AI + App Platform with state-of-the-art vision data + processing functionality, like occupancy + counting or person blur. Pretrained processor is + usually publicly available. + CUSTOM (2): + Processor Type CUSTOM. + Custom processors are specialized processors + which are either uploaded by customers or + imported from other GCP platform (for example + Vertex AI). Custom processor is only visible to + the creator. + CONNECTOR (3): + Processor Type CONNECTOR. + Connector processors are special processors + which perform I/O for the application, they do + not processing the data but either deliver the + data to other processors or receive data from + other processors. + """ + PROCESSOR_TYPE_UNSPECIFIED = 0 + PRETRAINED = 1 + CUSTOM = 2 + CONNECTOR = 3 + + class ProcessorState(proto.Enum): + r""" + + Values: + PROCESSOR_STATE_UNSPECIFIED (0): + Unspecified Processor state. + CREATING (1): + Processor is being created (not ready for + use). + ACTIVE (2): + Processor is and ready for use. + DELETING (3): + Processor is being deleted (not ready for + use). + FAILED (4): + Processor deleted or creation failed . + """ + PROCESSOR_STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + FAILED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=10, + ) + processor_type: ProcessorType = proto.Field( + proto.ENUM, + number=6, + enum=ProcessorType, + ) + model_type: 'ModelType' = proto.Field( + proto.ENUM, + number=13, + enum='ModelType', + ) + custom_processor_source_info: 'CustomProcessorSourceInfo' = proto.Field( + proto.MESSAGE, + number=7, + message='CustomProcessorSourceInfo', + ) + state: ProcessorState = proto.Field( + proto.ENUM, + number=8, + enum=ProcessorState, + ) + processor_io_spec: 'ProcessorIOSpec' = proto.Field( + proto.MESSAGE, + number=11, + message='ProcessorIOSpec', + ) + configuration_typeurl: str = proto.Field( + proto.STRING, + number=14, + ) + supported_annotation_types: MutableSequence[gcv_annotations.StreamAnnotationType] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=gcv_annotations.StreamAnnotationType, + ) + supports_post_processing: bool = proto.Field( + proto.BOOL, + number=17, + ) + supported_instance_types: MutableSequence['Instance.InstanceType'] = proto.RepeatedField( + proto.ENUM, + number=18, + enum='Instance.InstanceType', + ) + + +class ProcessorIOSpec(proto.Message): + r"""Message describing the input / output specifications of a + processor. + + Attributes: + graph_input_channel_specs (MutableSequence[google.cloud.visionai_v1.types.ProcessorIOSpec.GraphInputChannelSpec]): + For processors with input_channel_specs, the processor must + be explicitly connected to another processor. + graph_output_channel_specs (MutableSequence[google.cloud.visionai_v1.types.ProcessorIOSpec.GraphOutputChannelSpec]): + The output artifact specifications for the + current processor. + instance_resource_input_binding_specs (MutableSequence[google.cloud.visionai_v1.types.ProcessorIOSpec.InstanceResourceInputBindingSpec]): + The input resource that needs to be fed from + the application instance. + instance_resource_output_binding_specs (MutableSequence[google.cloud.visionai_v1.types.ProcessorIOSpec.InstanceResourceOutputBindingSpec]): + The output resource that the processor will + generate per instance. Other than the explicitly + listed output bindings here, all the processors' + GraphOutputChannels can be binded to stream + resource. The bind name then is the same as the + GraphOutputChannel's name. + """ + + class GraphInputChannelSpec(proto.Message): + r"""Message for input channel specification. + + Attributes: + name (str): + The name of the current input channel. + data_type (google.cloud.visionai_v1.types.DataType): + The data types of the current input channel. + When this field has more than 1 value, it means + this input channel can be connected to either of + these different data types. + accepted_data_type_uris (MutableSequence[str]): + If specified, only those detailed data types + can be connected to the processor. For example, + jpeg stream for MEDIA, or PredictionResult proto + for PROTO type. If unspecified, then any proto + is accepted. + required (bool): + Whether the current input channel is required + by the processor. For example, for a processor + with required video input and optional audio + input, if video input is missing, the + application will be rejected while the audio + input can be missing as long as the video input + exists. + max_connection_allowed (int): + How many input edges can be connected to this + input channel. 0 means unlimited. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_type: 'DataType' = proto.Field( + proto.ENUM, + number=2, + enum='DataType', + ) + accepted_data_type_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + required: bool = proto.Field( + proto.BOOL, + number=3, + ) + max_connection_allowed: int = proto.Field( + proto.INT64, + number=4, + ) + + class GraphOutputChannelSpec(proto.Message): + r"""Message for output channel specification. + + Attributes: + name (str): + The name of the current output channel. + data_type (google.cloud.visionai_v1.types.DataType): + The data type of the current output channel. + data_type_uri (str): + + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_type: 'DataType' = proto.Field( + proto.ENUM, + number=2, + enum='DataType', + ) + data_type_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + class InstanceResourceInputBindingSpec(proto.Message): + r"""Message for instance resource channel specification. + External resources are virtual nodes which are not expressed in + the application graph. Each processor expresses its out-graph + spec, so customer is able to override the external source or + destinations to the + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + config_type_uri (str): + The configuration proto that includes the + Googleapis resources. I.e. + type.googleapis.com/google.cloud.vision.v1.StreamWithAnnotation + + This field is a member of `oneof`_ ``resource_type``. + resource_type_uri (str): + The direct type url of Googleapis resource. + i.e. + type.googleapis.com/google.cloud.vision.v1.Asset + + This field is a member of `oneof`_ ``resource_type``. + name (str): + Name of the input binding, unique within the + processor. + """ + + config_type_uri: str = proto.Field( + proto.STRING, + number=2, + oneof='resource_type', + ) + resource_type_uri: str = proto.Field( + proto.STRING, + number=3, + oneof='resource_type', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class InstanceResourceOutputBindingSpec(proto.Message): + r""" + + Attributes: + name (str): + Name of the output binding, unique within the + processor. + resource_type_uri (str): + The resource type uri of the acceptable + output resource. + explicit (bool): + Whether the output resource needs to be + explicitly set in the instance. If it is false, + the processor will automatically generate it if + required. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type_uri: str = proto.Field( + proto.STRING, + number=2, + ) + explicit: bool = proto.Field( + proto.BOOL, + number=3, + ) + + graph_input_channel_specs: MutableSequence[GraphInputChannelSpec] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=GraphInputChannelSpec, + ) + graph_output_channel_specs: MutableSequence[GraphOutputChannelSpec] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=GraphOutputChannelSpec, + ) + instance_resource_input_binding_specs: MutableSequence[InstanceResourceInputBindingSpec] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=InstanceResourceInputBindingSpec, + ) + instance_resource_output_binding_specs: MutableSequence[InstanceResourceOutputBindingSpec] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=InstanceResourceOutputBindingSpec, + ) + + +class CustomProcessorSourceInfo(proto.Message): + r"""Describes the source info for a custom processor. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + vertex_model (str): + The resource name original model hosted in + the vertex AI platform. + + This field is a member of `oneof`_ ``artifact_path``. + product_recognizer_artifact (google.cloud.visionai_v1.types.CustomProcessorSourceInfo.ProductRecognizerArtifact): + Artifact for product recognizer. + + This field is a member of `oneof`_ ``artifact_path``. + source_type (google.cloud.visionai_v1.types.CustomProcessorSourceInfo.SourceType): + The original product which holds the custom + processor's functionality. + additional_info (MutableMapping[str, str]): + Output only. Additional info related to the + imported custom processor. Data is filled in by + app platform during the processor creation. + model_schema (google.cloud.visionai_v1.types.CustomProcessorSourceInfo.ModelSchema): + Model schema files which specifies the signature of the + model. For VERTEX_CUSTOM models, instances schema is + required. If instances schema is not specified during the + processor creation, VisionAI Platform will try to get it + from Vertex, if it doesn't exist, the creation will fail. + """ + class SourceType(proto.Enum): + r"""Source type of the imported custom processor. + + Values: + SOURCE_TYPE_UNSPECIFIED (0): + Source type unspecified. + VERTEX_AUTOML (1): + Custom processors coming from Vertex AutoML + product. + VERTEX_CUSTOM (2): + Custom processors coming from general custom + models from Vertex. + PRODUCT_RECOGNIZER (3): + Source for Product Recognizer. + """ + SOURCE_TYPE_UNSPECIFIED = 0 + VERTEX_AUTOML = 1 + VERTEX_CUSTOM = 2 + PRODUCT_RECOGNIZER = 3 + + class ProductRecognizerArtifact(proto.Message): + r"""Message describes product recognizer artifact. + + Attributes: + retail_product_recognition_index (str): + Required. Resource name of RetailProductRecognitionIndex. + Format is + 'projects/*/locations/*/retailCatalogs/*/retailProductRecognitionIndexes/*' + vertex_model (str): + Optional. The resource name of embedding + model hosted in Vertex AI Platform. + """ + + retail_product_recognition_index: str = proto.Field( + proto.STRING, + number=1, + ) + vertex_model: str = proto.Field( + proto.STRING, + number=2, + ) + + class ModelSchema(proto.Message): + r"""The schema is defined as an OpenAPI 3.0.2 `Schema + Object `__. + + Attributes: + instances_schema (google.cloud.visionai_v1.types.GcsSource): + Cloud Storage location to a YAML file that + defines the format of a single instance used in + prediction and explanation requests. + parameters_schema (google.cloud.visionai_v1.types.GcsSource): + Cloud Storage location to a YAML file that + defines the prediction and explanation + parameters. + predictions_schema (google.cloud.visionai_v1.types.GcsSource): + Cloud Storage location to a YAML file that + defines the format of a single prediction or + explanation. + """ + + instances_schema: common.GcsSource = proto.Field( + proto.MESSAGE, + number=1, + message=common.GcsSource, + ) + parameters_schema: common.GcsSource = proto.Field( + proto.MESSAGE, + number=2, + message=common.GcsSource, + ) + predictions_schema: common.GcsSource = proto.Field( + proto.MESSAGE, + number=3, + message=common.GcsSource, + ) + + vertex_model: str = proto.Field( + proto.STRING, + number=2, + oneof='artifact_path', + ) + product_recognizer_artifact: ProductRecognizerArtifact = proto.Field( + proto.MESSAGE, + number=3, + oneof='artifact_path', + message=ProductRecognizerArtifact, + ) + source_type: SourceType = proto.Field( + proto.ENUM, + number=1, + enum=SourceType, + ) + additional_info: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + model_schema: ModelSchema = proto.Field( + proto.MESSAGE, + number=5, + message=ModelSchema, + ) + + +class ProcessorConfig(proto.Message): + r"""Next ID: 35 + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + video_stream_input_config (google.cloud.visionai_v1.types.VideoStreamInputConfig): + Configs of stream input processor. + + This field is a member of `oneof`_ ``processor_config``. + ai_enabled_devices_input_config (google.cloud.visionai_v1.types.AIEnabledDevicesInputConfig): + Config of AI-enabled input devices. + + This field is a member of `oneof`_ ``processor_config``. + media_warehouse_config (google.cloud.visionai_v1.types.MediaWarehouseConfig): + Configs of media warehouse processor. + + This field is a member of `oneof`_ ``processor_config``. + person_blur_config (google.cloud.visionai_v1.types.PersonBlurConfig): + Configs of person blur processor. + + This field is a member of `oneof`_ ``processor_config``. + occupancy_count_config (google.cloud.visionai_v1.types.OccupancyCountConfig): + Configs of occupancy count processor. + + This field is a member of `oneof`_ ``processor_config``. + person_vehicle_detection_config (google.cloud.visionai_v1.types.PersonVehicleDetectionConfig): + Configs of Person Vehicle Detection + processor. + + This field is a member of `oneof`_ ``processor_config``. + vertex_automl_vision_config (google.cloud.visionai_v1.types.VertexAutoMLVisionConfig): + Configs of Vertex AutoML vision processor. + + This field is a member of `oneof`_ ``processor_config``. + vertex_automl_video_config (google.cloud.visionai_v1.types.VertexAutoMLVideoConfig): + Configs of Vertex AutoML video processor. + + This field is a member of `oneof`_ ``processor_config``. + vertex_custom_config (google.cloud.visionai_v1.types.VertexCustomConfig): + Configs of Vertex Custom processor. + + This field is a member of `oneof`_ ``processor_config``. + general_object_detection_config (google.cloud.visionai_v1.types.GeneralObjectDetectionConfig): + Configs of General Object Detection + processor. + + This field is a member of `oneof`_ ``processor_config``. + big_query_config (google.cloud.visionai_v1.types.BigQueryConfig): + Configs of BigQuery processor. + + This field is a member of `oneof`_ ``processor_config``. + gcs_output_config (google.cloud.visionai_v1.types.GcsOutputConfig): + Configs of Cloud Storage output processor. + + This field is a member of `oneof`_ ``processor_config``. + product_recognizer_config (google.cloud.visionai_v1.types.ProductRecognizerConfig): + Runtime configs of Product Recognizer + processor. + + This field is a member of `oneof`_ ``processor_config``. + personal_protective_equipment_detection_config (google.cloud.visionai_v1.types.PersonalProtectiveEquipmentDetectionConfig): + Configs of personal_protective_equipment_detection_config + + This field is a member of `oneof`_ ``processor_config``. + tag_recognizer_config (google.cloud.visionai_v1.types.TagRecognizerConfig): + Runtime configs of Tag Recognizer processor. + + This field is a member of `oneof`_ ``processor_config``. + universal_input_config (google.cloud.visionai_v1.types.UniversalInputConfig): + Runtime configs of UniversalInput processor. + + This field is a member of `oneof`_ ``processor_config``. + experimental_config (google.protobuf.struct_pb2.Struct): + Experimental configurations. Structured + object containing not-yet-stable processor + parameters. + """ + + video_stream_input_config: 'VideoStreamInputConfig' = proto.Field( + proto.MESSAGE, + number=9, + oneof='processor_config', + message='VideoStreamInputConfig', + ) + ai_enabled_devices_input_config: 'AIEnabledDevicesInputConfig' = proto.Field( + proto.MESSAGE, + number=20, + oneof='processor_config', + message='AIEnabledDevicesInputConfig', + ) + media_warehouse_config: 'MediaWarehouseConfig' = proto.Field( + proto.MESSAGE, + number=10, + oneof='processor_config', + message='MediaWarehouseConfig', + ) + person_blur_config: 'PersonBlurConfig' = proto.Field( + proto.MESSAGE, + number=11, + oneof='processor_config', + message='PersonBlurConfig', + ) + occupancy_count_config: 'OccupancyCountConfig' = proto.Field( + proto.MESSAGE, + number=12, + oneof='processor_config', + message='OccupancyCountConfig', + ) + person_vehicle_detection_config: 'PersonVehicleDetectionConfig' = proto.Field( + proto.MESSAGE, + number=15, + oneof='processor_config', + message='PersonVehicleDetectionConfig', + ) + vertex_automl_vision_config: 'VertexAutoMLVisionConfig' = proto.Field( + proto.MESSAGE, + number=13, + oneof='processor_config', + message='VertexAutoMLVisionConfig', + ) + vertex_automl_video_config: 'VertexAutoMLVideoConfig' = proto.Field( + proto.MESSAGE, + number=14, + oneof='processor_config', + message='VertexAutoMLVideoConfig', + ) + vertex_custom_config: 'VertexCustomConfig' = proto.Field( + proto.MESSAGE, + number=17, + oneof='processor_config', + message='VertexCustomConfig', + ) + general_object_detection_config: 'GeneralObjectDetectionConfig' = proto.Field( + proto.MESSAGE, + number=18, + oneof='processor_config', + message='GeneralObjectDetectionConfig', + ) + big_query_config: 'BigQueryConfig' = proto.Field( + proto.MESSAGE, + number=19, + oneof='processor_config', + message='BigQueryConfig', + ) + gcs_output_config: 'GcsOutputConfig' = proto.Field( + proto.MESSAGE, + number=27, + oneof='processor_config', + message='GcsOutputConfig', + ) + product_recognizer_config: 'ProductRecognizerConfig' = proto.Field( + proto.MESSAGE, + number=21, + oneof='processor_config', + message='ProductRecognizerConfig', + ) + personal_protective_equipment_detection_config: 'PersonalProtectiveEquipmentDetectionConfig' = proto.Field( + proto.MESSAGE, + number=22, + oneof='processor_config', + message='PersonalProtectiveEquipmentDetectionConfig', + ) + tag_recognizer_config: 'TagRecognizerConfig' = proto.Field( + proto.MESSAGE, + number=25, + oneof='processor_config', + message='TagRecognizerConfig', + ) + universal_input_config: 'UniversalInputConfig' = proto.Field( + proto.MESSAGE, + number=28, + oneof='processor_config', + message='UniversalInputConfig', + ) + experimental_config: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=26, + message=struct_pb2.Struct, + ) + + +class StreamWithAnnotation(proto.Message): + r"""Message describing Vision AI stream with application specific + annotations. All the StreamAnnotation object inside this message + MUST have unique id. + + Attributes: + stream (str): + Vision AI Stream resource name. + application_annotations (MutableSequence[google.cloud.visionai_v1.types.StreamAnnotation]): + Annotations that will be applied to the whole + application. + node_annotations (MutableSequence[google.cloud.visionai_v1.types.StreamWithAnnotation.NodeAnnotation]): + Annotations that will be applied to the + specific node of the application. If the same + type of the annotations is applied to both + application and node, the node annotation will + be added in addition to the global application + one. + For example, if there is one active zone + annotation for the whole application and one + active zone annotation for the Occupancy + Analytic processor, then the Occupancy Analytic + processor will have two active zones defined. + """ + + class NodeAnnotation(proto.Message): + r"""Message describing annotations specific to application node. + + Attributes: + node (str): + The node name of the application graph. + annotations (MutableSequence[google.cloud.visionai_v1.types.StreamAnnotation]): + The node specific stream annotations. + """ + + node: str = proto.Field( + proto.STRING, + number=1, + ) + annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcv_annotations.StreamAnnotation, + ) + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + application_annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcv_annotations.StreamAnnotation, + ) + node_annotations: MutableSequence[NodeAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=NodeAnnotation, + ) + + +class ApplicationNodeAnnotation(proto.Message): + r"""Message describing annotations specific to application node. + This message is a duplication of + StreamWithAnnotation.NodeAnnotation. + + Attributes: + node (str): + The node name of the application graph. + annotations (MutableSequence[google.cloud.visionai_v1.types.StreamAnnotation]): + The node specific stream annotations. + """ + + node: str = proto.Field( + proto.STRING, + number=1, + ) + annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcv_annotations.StreamAnnotation, + ) + + +class ResourceAnnotations(proto.Message): + r"""Message describing general annotation for resources. + + Attributes: + application_annotations (MutableSequence[google.cloud.visionai_v1.types.StreamAnnotation]): + Annotations that will be applied to the whole + application. + node_annotations (MutableSequence[google.cloud.visionai_v1.types.ApplicationNodeAnnotation]): + Annotations that will be applied to the + specific node of the application. If the same + type of the annotations is applied to both + application and node, the node annotation will + be added in addition to the global application + one. + For example, if there is one active zone + annotation for the whole application and one + active zone annotation for the Occupancy + Analytic processor, then the Occupancy Analytic + processor will have two active zones defined. + """ + + application_annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcv_annotations.StreamAnnotation, + ) + node_annotations: MutableSequence['ApplicationNodeAnnotation'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationNodeAnnotation', + ) + + +class VideoStreamInputConfig(proto.Message): + r"""Message describing Video Stream Input Config. + This message should only be used as a placeholder for + builtin:stream-input processor, actual stream binding should be + specified using corresponding API. + + Attributes: + streams (MutableSequence[str]): + + streams_with_annotation (MutableSequence[google.cloud.visionai_v1.types.StreamWithAnnotation]): + + """ + + streams: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + streams_with_annotation: MutableSequence['StreamWithAnnotation'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='StreamWithAnnotation', + ) + + +class AIEnabledDevicesInputConfig(proto.Message): + r"""Message describing AI-enabled Devices Input Config. + """ + + +class MediaWarehouseConfig(proto.Message): + r"""Message describing MediaWarehouseConfig. + + Attributes: + corpus (str): + Resource name of the Media Warehouse corpus. Format: + projects/${project_id}/locations/${location_id}/corpora/${corpus_id} + region (str): + Deprecated. + ttl (google.protobuf.duration_pb2.Duration): + The duration for which all media assets, + associated metadata, and search documents can + exist. + """ + + corpus: str = proto.Field( + proto.STRING, + number=1, + ) + region: str = proto.Field( + proto.STRING, + number=2, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + +class PersonBlurConfig(proto.Message): + r"""Message describing FaceBlurConfig. + + Attributes: + person_blur_type (google.cloud.visionai_v1.types.PersonBlurConfig.PersonBlurType): + Person blur type. + faces_only (bool): + Whether only blur faces other than the whole + object in the processor. + """ + class PersonBlurType(proto.Enum): + r"""Type of Person Blur + + Values: + PERSON_BLUR_TYPE_UNSPECIFIED (0): + PersonBlur Type UNSPECIFIED. + FULL_OCCULUSION (1): + FaceBlur Type full occlusion. + BLUR_FILTER (2): + FaceBlur Type blur filter. + """ + PERSON_BLUR_TYPE_UNSPECIFIED = 0 + FULL_OCCULUSION = 1 + BLUR_FILTER = 2 + + person_blur_type: PersonBlurType = proto.Field( + proto.ENUM, + number=1, + enum=PersonBlurType, + ) + faces_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class OccupancyCountConfig(proto.Message): + r"""Message describing OccupancyCountConfig. + + Attributes: + enable_people_counting (bool): + Whether to count the appearances of people, + output counts have 'people' as the key. + enable_vehicle_counting (bool): + Whether to count the appearances of vehicles, + output counts will have 'vehicle' as the key. + enable_dwelling_time_tracking (bool): + Whether to track each invidual object's + loitering time inside the scene or specific + zone. + """ + + enable_people_counting: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vehicle_counting: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_dwelling_time_tracking: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PersonVehicleDetectionConfig(proto.Message): + r"""Message describing PersonVehicleDetectionConfig. + + Attributes: + enable_people_counting (bool): + At least one of enable_people_counting and + enable_vehicle_counting fields must be set to true. Whether + to count the appearances of people, output counts have + 'people' as the key. + enable_vehicle_counting (bool): + Whether to count the appearances of vehicles, + output counts will have 'vehicle' as the key. + """ + + enable_people_counting: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vehicle_counting: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class PersonalProtectiveEquipmentDetectionConfig(proto.Message): + r"""Message describing + PersonalProtectiveEquipmentDetectionConfig. + + Attributes: + enable_face_coverage_detection (bool): + Whether to enable face coverage detection. + enable_head_coverage_detection (bool): + Whether to enable head coverage detection. + enable_hands_coverage_detection (bool): + Whether to enable hands coverage detection. + """ + + enable_face_coverage_detection: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_head_coverage_detection: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_hands_coverage_detection: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GeneralObjectDetectionConfig(proto.Message): + r"""Message of configurations for General Object Detection + processor. + + """ + + +class BigQueryConfig(proto.Message): + r"""Message of configurations for BigQuery processor. + + Attributes: + table (str): + BigQuery table resource for Vision AI + Platform to ingest annotations to. + cloud_function_mapping (MutableMapping[str, str]): + Data Schema By default, Vision AI Application will try to + write annotations to the target BigQuery table using the + following schema: + + ingestion_time: TIMESTAMP, the ingestion time of the + original data. + + application: STRING, name of the application which produces + the annotation. + + instance: STRING, Id of the instance which produces the + annotation. + + node: STRING, name of the application graph node which + produces the annotation. + + annotation: STRING or JSON, the actual annotation protobuf + will be converted to json string with bytes field as 64 + encoded string. It can be written to both String or Json + type column. + + To forward annotation data to an existing BigQuery table, + customer needs to make sure the compatibility of the schema. + The map maps application node name to its corresponding + cloud function endpoint to transform the annotations + directly to the + google.cloud.bigquery.storage.v1.AppendRowsRequest (only + avro_rows or proto_rows should be set). If configured, + annotations produced by corresponding application node will + sent to the Cloud Function at first before be forwarded to + BigQuery. + + If the default table schema doesn't fit, customer is able to + transform the annotation output from Vision AI Application + to arbitrary BigQuery table schema with CloudFunction. + + - The cloud function will receive + AppPlatformCloudFunctionRequest where the annotations + field will be the json format of Vision AI annotation. + - The cloud function should return + AppPlatformCloudFunctionResponse with AppendRowsRequest + stored in the annotations field. + - To drop the annotation, simply clear the annotations + field in the returned AppPlatformCloudFunctionResponse. + create_default_table_if_not_exists (bool): + If true, App Platform will create the + BigQuery DataSet and the BigQuery Table with + default schema if the specified table doesn't + exist. This doesn't work if any cloud function + customized schema is specified since the system + doesn't know your desired schema. JSON column + will be used in the default table created by App + Platform. + """ + + table: str = proto.Field( + proto.STRING, + number=1, + ) + cloud_function_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + create_default_table_if_not_exists: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class VertexAutoMLVisionConfig(proto.Message): + r"""Message of configurations of Vertex AutoML Vision Processors. + + Attributes: + confidence_threshold (float): + Only entities with higher score than the + threshold will be returned. Value 0.0 means to + return all the detected entities. + max_predictions (int): + At most this many predictions will be + returned per output frame. Value 0 means to + return all the detected entities. + """ + + confidence_threshold: float = proto.Field( + proto.FLOAT, + number=1, + ) + max_predictions: int = proto.Field( + proto.INT32, + number=2, + ) + + +class VertexAutoMLVideoConfig(proto.Message): + r"""Message describing VertexAutoMLVideoConfig. + + Attributes: + confidence_threshold (float): + Only entities with higher score than the + threshold will be returned. Value 0.0 means + returns all the detected entities. + blocked_labels (MutableSequence[str]): + Labels specified in this field won't be + returned. + max_predictions (int): + At most this many predictions will be + returned per output frame. Value 0 means to + return all the detected entities. + bounding_box_size_limit (float): + Only Bounding Box whose size is larger than + this limit will be returned. Object Tracking + only. Value 0.0 means to return all the detected + entities. + """ + + confidence_threshold: float = proto.Field( + proto.FLOAT, + number=1, + ) + blocked_labels: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + max_predictions: int = proto.Field( + proto.INT32, + number=3, + ) + bounding_box_size_limit: float = proto.Field( + proto.FLOAT, + number=4, + ) + + +class VertexCustomConfig(proto.Message): + r"""Message describing VertexCustomConfig. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_prediction_fps (int): + The max prediction frame per second. This + attribute sets how fast the operator sends + prediction requests to Vertex AI endpoint. + Default value is 0, which means there is no max + prediction fps limit. The operator sends + prediction requests at input fps. + dedicated_resources (google.cloud.visionai_v1.types.DedicatedResources): + A description of resources that are dedicated + to the DeployedModel, and that need a higher + degree of manual configuration. + post_processing_cloud_function (str): + If not empty, the prediction result will be sent to the + specified cloud function for post processing. + + - The cloud function will receive + AppPlatformCloudFunctionRequest where the annotations + field will be the json format of proto PredictResponse. + - The cloud function should return + AppPlatformCloudFunctionResponse with PredictResponse + stored in the annotations field. + - To drop the prediction output, simply clear the payload + field in the returned AppPlatformCloudFunctionResponse. + attach_application_metadata (bool): + If true, the prediction request received by + custom model will also contain metadata with the + following schema: + + 'appPlatformMetadata': { + 'ingestionTime': DOUBLE; (UNIX timestamp) + 'application': STRING; + 'instanceId': STRING; + 'node': STRING; + 'processor': STRING; + } + dynamic_config_input_topic (str): + Optional. By setting the configuration_input_topic, + processor will subscribe to given topic, only pub/sub topic + is supported now. Example channel: + //pubsub.googleapis.com/projects/visionai-testing-stable/topics/test-topic + message schema should be: message Message { // The ID of the + stream that associates with the application instance. string + stream_id = 1; // The target fps. By default, the custom + processor will *not* send any data to the Vertex Prediction + container. Note that once the dynamic_config_input_topic is + set, max_prediction_fps will not work and be preceded by the + fps set inside the topic. int32 fps = 2; } + + This field is a member of `oneof`_ ``_dynamic_config_input_topic``. + """ + + max_prediction_fps: int = proto.Field( + proto.INT32, + number=1, + ) + dedicated_resources: 'DedicatedResources' = proto.Field( + proto.MESSAGE, + number=2, + message='DedicatedResources', + ) + post_processing_cloud_function: str = proto.Field( + proto.STRING, + number=3, + ) + attach_application_metadata: bool = proto.Field( + proto.BOOL, + number=4, + ) + dynamic_config_input_topic: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + +class GcsOutputConfig(proto.Message): + r"""Message describing GcsOutputConfig. + + Attributes: + gcs_path (str): + The Cloud Storage path for Vision AI Platform + to ingest annotations to. + """ + + gcs_path: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UniversalInputConfig(proto.Message): + r"""Message describing UniversalInputConfig. + """ + + +class MachineSpec(proto.Message): + r"""Specification of a single machine. + + Attributes: + machine_type (str): + Immutable. The type of the machine. + + See the `list of machine types supported for + prediction `__ + + See the `list of machine types supported for custom + training `__. + + For [DeployedModel][] this field is optional, and the + default value is ``n1-standard-2``. For + [BatchPredictionJob][] or as part of [WorkerPoolSpec][] this + field is required. + accelerator_type (google.cloud.visionai_v1.types.AcceleratorType): + Immutable. The type of accelerator(s) that may be attached + to the machine as per + [accelerator_count][google.cloud.visionai.v1.MachineSpec.accelerator_count]. + accelerator_count (int): + The number of accelerators to attach to the + machine. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + accelerator_type: 'AcceleratorType' = proto.Field( + proto.ENUM, + number=2, + enum='AcceleratorType', + ) + accelerator_count: int = proto.Field( + proto.INT32, + number=3, + ) + + +class AutoscalingMetricSpec(proto.Message): + r"""The metric specification that defines the target resource + utilization (CPU utilization, accelerator's duty cycle, and so + on) for calculating the desired replica count. + + Attributes: + metric_name (str): + Required. The resource metric name. Supported metrics: + + - For Online Prediction: + - ``aiplatform.googleapis.com/prediction/online/accelerator/duty_cycle`` + - ``aiplatform.googleapis.com/prediction/online/cpu/utilization`` + target (int): + The target resource utilization in percentage + (1% - 100%) for the given metric; once the real + usage deviates from the target by a certain + percentage, the machine replicas change. The + default value is 60 (representing 60%) if not + provided. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + target: int = proto.Field( + proto.INT32, + number=2, + ) + + +class DedicatedResources(proto.Message): + r"""A description of resources that are dedicated to a + DeployedModel, and that need a higher degree of manual + configuration. + + Attributes: + machine_spec (google.cloud.visionai_v1.types.MachineSpec): + Required. Immutable. The specification of a + single machine used by the prediction. + min_replica_count (int): + Required. Immutable. The minimum number of + machine replicas this DeployedModel will be + always deployed on. This value must be greater + than or equal to 1. + + If traffic against the DeployedModel increases, + it may dynamically be deployed onto more + replicas, and as traffic decreases, some of + these extra replicas may be freed. + max_replica_count (int): + Immutable. The maximum number of replicas this DeployedModel + may be deployed on when the traffic against it increases. If + the requested value is too large, the deployment will error, + but if deployment succeeds then the ability to scale the + model to that many replicas is guaranteed (barring service + outages). If traffic against the DeployedModel increases + beyond what its replicas at maximum may handle, a portion of + the traffic will be dropped. If this value is not provided, + will use + [min_replica_count][google.cloud.visionai.v1.DedicatedResources.min_replica_count] + as the default value. + + The value of this field impacts the charge against Vertex + CPU and GPU quotas. Specifically, you will be charged for + max_replica_count \* number of cores in the selected machine + type) and (max_replica_count \* number of GPUs per replica + in the selected machine type). + autoscaling_metric_specs (MutableSequence[google.cloud.visionai_v1.types.AutoscalingMetricSpec]): + Immutable. The metric specifications that overrides a + resource utilization metric (CPU utilization, accelerator's + duty cycle, and so on) target value (default to 60 if not + set). At most one entry is allowed per metric. + + If + [machine_spec.accelerator_count][google.cloud.visionai.v1.MachineSpec.accelerator_count] + is above 0, the autoscaling will be based on both CPU + utilization and accelerator's duty cycle metrics and scale + up when either metrics exceeds its target value while scale + down if both metrics are under their target value. The + default target value is 60 for both metrics. + + If + [machine_spec.accelerator_count][google.cloud.visionai.v1.MachineSpec.accelerator_count] + is 0, the autoscaling will be based on CPU utilization + metric only with default target value 60 if not explicitly + set. + + For example, in the case of Online Prediction, if you want + to override target CPU utilization to 80, you should set + [autoscaling_metric_specs.metric_name][google.cloud.visionai.v1.AutoscalingMetricSpec.metric_name] + to + ``aiplatform.googleapis.com/prediction/online/cpu/utilization`` + and + [autoscaling_metric_specs.target][google.cloud.visionai.v1.AutoscalingMetricSpec.target] + to ``80``. + """ + + machine_spec: 'MachineSpec' = proto.Field( + proto.MESSAGE, + number=1, + message='MachineSpec', + ) + min_replica_count: int = proto.Field( + proto.INT32, + number=2, + ) + max_replica_count: int = proto.Field( + proto.INT32, + number=3, + ) + autoscaling_metric_specs: MutableSequence['AutoscalingMetricSpec'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AutoscalingMetricSpec', + ) + + +class ProductRecognizerConfig(proto.Message): + r"""Message describing ProductRecognizerConfig. + + Attributes: + retail_endpoint (str): + The resource name of retail endpoint to use. + recognition_confidence_threshold (float): + Confidence threshold to filter detection + results. If not set, a system default value will + be used. + """ + + retail_endpoint: str = proto.Field( + proto.STRING, + number=1, + ) + recognition_confidence_threshold: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class TagRecognizerConfig(proto.Message): + r"""Message describing TagRecognizerConfig. + + Attributes: + entity_detection_confidence_threshold (float): + Confidence threshold to filter detection + results. If not set, a system default value will + be used. + tag_parsing_config (google.cloud.visionai_v1.types.TagParsingConfig): + Configuration to customize how tags are + parsed. + """ + + entity_detection_confidence_threshold: float = proto.Field( + proto.FLOAT, + number=1, + ) + tag_parsing_config: 'TagParsingConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='TagParsingConfig', + ) + + +class TagParsingConfig(proto.Message): + r"""Configuration for tag parsing. + + Attributes: + entity_parsing_configs (MutableSequence[google.cloud.visionai_v1.types.TagParsingConfig.EntityParsingConfig]): + Each tag entity class may have an optional + EntityParsingConfig which is used to help parse + the entities of the class. + """ + + class EntityParsingConfig(proto.Message): + r"""Configuration for parsing a tag entity class. + + Attributes: + entity_class (str): + Required. The tag entity class name. This + should match the class name produced by the tag + entity detection model. + regex (str): + Optional. An regular expression hint. + entity_matching_strategy (google.cloud.visionai_v1.types.TagParsingConfig.EntityParsingConfig.EntityMatchingStrategy): + Optional. Entity matching strategy. + """ + class EntityMatchingStrategy(proto.Enum): + r"""Type of entity matching strategy. + + Values: + ENTITY_MATCHING_STRATEGY_UNSPECIFIED (0): + If unspecified, multi-line matching will be + used by default. + MULTI_LINE_MATCHING (1): + Matches multiple lines of text. + MAX_OVERLAP_AREA (2): + Matches the line with the maximum overlap + area with entity bounding box. + """ + ENTITY_MATCHING_STRATEGY_UNSPECIFIED = 0 + MULTI_LINE_MATCHING = 1 + MAX_OVERLAP_AREA = 2 + + entity_class: str = proto.Field( + proto.STRING, + number=1, + ) + regex: str = proto.Field( + proto.STRING, + number=2, + ) + entity_matching_strategy: 'TagParsingConfig.EntityParsingConfig.EntityMatchingStrategy' = proto.Field( + proto.ENUM, + number=3, + enum='TagParsingConfig.EntityParsingConfig.EntityMatchingStrategy', + ) + + entity_parsing_configs: MutableSequence[EntityParsingConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=EntityParsingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streaming_resources.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streaming_resources.py new file mode 100644 index 000000000000..c274f64711b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streaming_resources.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'GstreamerBufferDescriptor', + 'RawImageDescriptor', + 'PacketType', + 'ServerMetadata', + 'SeriesMetadata', + 'PacketHeader', + 'Packet', + }, +) + + +class GstreamerBufferDescriptor(proto.Message): + r"""The descriptor for a gstreamer buffer payload. + + Attributes: + caps_string (str): + The caps string of the payload. + is_key_frame (bool): + Whether the buffer is a key frame. + pts_time (google.protobuf.timestamp_pb2.Timestamp): + PTS of the frame. + dts_time (google.protobuf.timestamp_pb2.Timestamp): + DTS of the frame. + duration (google.protobuf.duration_pb2.Duration): + Duration of the frame. + """ + + caps_string: str = proto.Field( + proto.STRING, + number=1, + ) + is_key_frame: bool = proto.Field( + proto.BOOL, + number=2, + ) + pts_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + dts_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + +class RawImageDescriptor(proto.Message): + r"""The descriptor for a raw image. + + Attributes: + format_ (str): + Raw image format. Its possible values are: + "srgb". + height (int): + The height of the image. + width (int): + The width of the image. + """ + + format_: str = proto.Field( + proto.STRING, + number=1, + ) + height: int = proto.Field( + proto.INT32, + number=2, + ) + width: int = proto.Field( + proto.INT32, + number=3, + ) + + +class PacketType(proto.Message): + r"""The message that represents the data type of a packet. + + Attributes: + type_class (str): + The type class of the packet. Its possible + values are: "gst", "protobuf", and "string". + type_descriptor (google.cloud.visionai_v1.types.PacketType.TypeDescriptor): + The type descriptor. + """ + + class TypeDescriptor(proto.Message): + r"""The message that fully specifies the type of the packet. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gstreamer_buffer_descriptor (google.cloud.visionai_v1.types.GstreamerBufferDescriptor): + GstreamerBufferDescriptor is the descriptor + for gstreamer buffer type. + + This field is a member of `oneof`_ ``type_details``. + raw_image_descriptor (google.cloud.visionai_v1.types.RawImageDescriptor): + RawImageDescriptor is the descriptor for the + raw image type. + + This field is a member of `oneof`_ ``type_details``. + type_ (str): + The type of the packet. Its possible values is codec + dependent. + + The fully qualified type name is always the concatenation of + the value in ``type_class`` together with the value in + ``type``, separated by a '/'. + + Note that specific codecs can define their own type + hierarchy, and so the type string here can in fact be + separated by multiple '/'s of its own. + + Please see the open source SDK for specific codec + documentation. + """ + + gstreamer_buffer_descriptor: 'GstreamerBufferDescriptor' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type_details', + message='GstreamerBufferDescriptor', + ) + raw_image_descriptor: 'RawImageDescriptor' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type_details', + message='RawImageDescriptor', + ) + type_: str = proto.Field( + proto.STRING, + number=1, + ) + + type_class: str = proto.Field( + proto.STRING, + number=1, + ) + type_descriptor: TypeDescriptor = proto.Field( + proto.MESSAGE, + number=2, + message=TypeDescriptor, + ) + + +class ServerMetadata(proto.Message): + r"""The message that represents server metadata. + + Attributes: + offset (int): + The offset position for the packet in its + stream. + ingest_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the stream server + receives this packet. This is based on the local + clock of on the server side. It is guaranteed to + be monotonically increasing for the packets + within each session; however this timestamp is + not comparable across packets sent to the same + stream different sessions. Session here refers + to one individual gRPC streaming request to the + stream server. + """ + + offset: int = proto.Field( + proto.INT64, + number=1, + ) + ingest_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class SeriesMetadata(proto.Message): + r"""The message that represents series metadata. + + Attributes: + series (str): + Series name. It's in the format of + "projects/{project}/locations/{location}/clusters/{cluster}/series/{stream}". + """ + + series: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PacketHeader(proto.Message): + r"""The message that represents packet header. + + Attributes: + capture_time (google.protobuf.timestamp_pb2.Timestamp): + Input only. The capture time of the packet. + type_ (google.cloud.visionai_v1.types.PacketType): + Input only. Immutable. The type of the + payload. + metadata (google.protobuf.struct_pb2.Struct): + Input only. This field is for users to attach + user managed metadata. + server_metadata (google.cloud.visionai_v1.types.ServerMetadata): + Output only. Metadata that the server appends + to each packet before sending it to receivers. + You don't need to set a value for this field + when sending packets. + series_metadata (google.cloud.visionai_v1.types.SeriesMetadata): + Input only. Immutable. Metadata that the + server needs to know where to write the packets + to. It's only required for the first packet. + flags (int): + Immutable. Packet flag set. SDK will set the + flag automatically. + trace_context (str): + Immutable. Header string for tracing across services. It + should be set when the packet is first arrived in the stream + server. + + The input format is a lowercase hex string: + + - version_id: 1 byte, currently must be zero - hex encoded + (2 characters) + - trace_id: 16 bytes (opaque blob) - hex encoded (32 + characters) + - span_id: 8 bytes (opaque blob) - hex encoded (16 + characters) + - trace_options: 1 byte (LSB means tracing enabled) - hex + encoded (2 characters) Example: + "00-404142434445464748494a4b4c4d4e4f-6162636465666768-01" + v trace_id span_id options + """ + + capture_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + type_: 'PacketType' = proto.Field( + proto.MESSAGE, + number=2, + message='PacketType', + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + server_metadata: 'ServerMetadata' = proto.Field( + proto.MESSAGE, + number=4, + message='ServerMetadata', + ) + series_metadata: 'SeriesMetadata' = proto.Field( + proto.MESSAGE, + number=5, + message='SeriesMetadata', + ) + flags: int = proto.Field( + proto.INT32, + number=6, + ) + trace_context: str = proto.Field( + proto.STRING, + number=7, + ) + + +class Packet(proto.Message): + r"""The quanta of datum that the series accepts. + + Attributes: + header (google.cloud.visionai_v1.types.PacketHeader): + The packet header. + payload (bytes): + The payload of the packet. + """ + + header: 'PacketHeader' = proto.Field( + proto.MESSAGE, + number=1, + message='PacketHeader', + ) + payload: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streaming_service.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streaming_service.py new file mode 100644 index 000000000000..8271c9e8bde7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streaming_service.py @@ -0,0 +1,780 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1.types import streaming_resources +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'LeaseType', + 'ReceiveEventsRequest', + 'EventUpdate', + 'ReceiveEventsControlResponse', + 'ReceiveEventsResponse', + 'Lease', + 'AcquireLeaseRequest', + 'RenewLeaseRequest', + 'ReleaseLeaseRequest', + 'ReleaseLeaseResponse', + 'RequestMetadata', + 'SendPacketsRequest', + 'SendPacketsResponse', + 'ReceivePacketsRequest', + 'ReceivePacketsControlResponse', + 'ReceivePacketsResponse', + 'EagerMode', + 'ControlledMode', + 'CommitRequest', + }, +) + + +class LeaseType(proto.Enum): + r"""The lease type. + + Values: + LEASE_TYPE_UNSPECIFIED (0): + Lease type unspecified. + LEASE_TYPE_READER (1): + Lease for stream reader. + LEASE_TYPE_WRITER (2): + Lease for stream writer. + """ + LEASE_TYPE_UNSPECIFIED = 0 + LEASE_TYPE_READER = 1 + LEASE_TYPE_WRITER = 2 + + +class ReceiveEventsRequest(proto.Message): + r"""Request message for ReceiveEvents. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + setup_request (google.cloud.visionai_v1.types.ReceiveEventsRequest.SetupRequest): + The setup request to setup the RPC + connection. + + This field is a member of `oneof`_ ``request``. + commit_request (google.cloud.visionai_v1.types.CommitRequest): + This request checkpoints the consumer's read + progress. + + This field is a member of `oneof`_ ``request``. + """ + + class SetupRequest(proto.Message): + r"""SetupRequest is the first message sent to the service to + setup the RPC connection. + + Attributes: + cluster (str): + The cluster name. + stream (str): + The stream name. The service will return the + events for the given stream. + receiver (str): + A name for the receiver to self-identify. + + This is used to keep track of a receiver's read + progress. + controlled_mode (google.cloud.visionai_v1.types.ControlledMode): + Controller mode configuration for receiving + events from the server. + heartbeat_interval (google.protobuf.duration_pb2.Duration): + The maximum duration of server silence before the client + determines the server unreachable. + + The client must either receive an ``Event`` update or a + heart beat message before this duration expires; otherwise, + the client will automatically cancel the current connection + and retry. + writes_done_grace_period (google.protobuf.duration_pb2.Duration): + The grace period after which a ``writes_done_request`` is + issued, that a ``WritesDone`` is expected from the client. + + The server is free to cancel the RPC should this expire. + + A system default will be chosen if unset. + """ + + cluster: str = proto.Field( + proto.STRING, + number=1, + ) + stream: str = proto.Field( + proto.STRING, + number=2, + ) + receiver: str = proto.Field( + proto.STRING, + number=3, + ) + controlled_mode: 'ControlledMode' = proto.Field( + proto.MESSAGE, + number=4, + message='ControlledMode', + ) + heartbeat_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + writes_done_grace_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + setup_request: SetupRequest = proto.Field( + proto.MESSAGE, + number=1, + oneof='request', + message=SetupRequest, + ) + commit_request: 'CommitRequest' = proto.Field( + proto.MESSAGE, + number=2, + oneof='request', + message='CommitRequest', + ) + + +class EventUpdate(proto.Message): + r"""The event update message. + + Attributes: + stream (str): + The name of the stream that the event is + attached to. + event (str): + The name of the event. + series (str): + The name of the series. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the Event update happens. + offset (int): + The offset of the message that will be used + to acknowledge of the message receiving. + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + event: str = proto.Field( + proto.STRING, + number=2, + ) + series: str = proto.Field( + proto.STRING, + number=3, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + offset: int = proto.Field( + proto.INT64, + number=5, + ) + + +class ReceiveEventsControlResponse(proto.Message): + r"""Control message for a ReceiveEventsResponse. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + heartbeat (bool): + A server heartbeat. + + This field is a member of `oneof`_ ``control``. + writes_done_request (bool): + A request to the receiver to complete any final writes + followed by a ``WritesDone``; e.g. issue any final + ``CommitRequest``\ s. + + May be ignored if ``WritesDone`` has already been issued at + any point prior to receiving this message. + + If ``WritesDone`` does not get issued, then the server will + forcefully cancel the connection, and the receiver will + likely receive an uninformative after ``Read`` returns + ``false`` and ``Finish`` is called. + + This field is a member of `oneof`_ ``control``. + """ + + heartbeat: bool = proto.Field( + proto.BOOL, + number=1, + oneof='control', + ) + writes_done_request: bool = proto.Field( + proto.BOOL, + number=2, + oneof='control', + ) + + +class ReceiveEventsResponse(proto.Message): + r"""Response message for the ReceiveEvents. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + event_update (google.cloud.visionai_v1.types.EventUpdate): + The event update message. + + This field is a member of `oneof`_ ``response``. + control (google.cloud.visionai_v1.types.ReceiveEventsControlResponse): + A control message from the server. + + This field is a member of `oneof`_ ``response``. + """ + + event_update: 'EventUpdate' = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message='EventUpdate', + ) + control: 'ReceiveEventsControlResponse' = proto.Field( + proto.MESSAGE, + number=2, + oneof='response', + message='ReceiveEventsControlResponse', + ) + + +class Lease(proto.Message): + r"""The lease message. + + Attributes: + id (str): + The lease id. + series (str): + The series name. + owner (str): + The owner name. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The lease expire time. + lease_type (google.cloud.visionai_v1.types.LeaseType): + The lease type. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + series: str = proto.Field( + proto.STRING, + number=2, + ) + owner: str = proto.Field( + proto.STRING, + number=3, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + lease_type: 'LeaseType' = proto.Field( + proto.ENUM, + number=5, + enum='LeaseType', + ) + + +class AcquireLeaseRequest(proto.Message): + r"""Request message for acquiring a lease. + + Attributes: + series (str): + The series name. + owner (str): + The owner name. + term (google.protobuf.duration_pb2.Duration): + The lease term. + lease_type (google.cloud.visionai_v1.types.LeaseType): + The lease type. + """ + + series: str = proto.Field( + proto.STRING, + number=1, + ) + owner: str = proto.Field( + proto.STRING, + number=2, + ) + term: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + lease_type: 'LeaseType' = proto.Field( + proto.ENUM, + number=4, + enum='LeaseType', + ) + + +class RenewLeaseRequest(proto.Message): + r"""Request message for renewing a lease. + + Attributes: + id (str): + Lease id. + series (str): + Series name. + owner (str): + Lease owner. + term (google.protobuf.duration_pb2.Duration): + Lease term. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + series: str = proto.Field( + proto.STRING, + number=2, + ) + owner: str = proto.Field( + proto.STRING, + number=3, + ) + term: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + + +class ReleaseLeaseRequest(proto.Message): + r"""Request message for releasing lease. + + Attributes: + id (str): + Lease id. + series (str): + Series name. + owner (str): + Lease owner. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + series: str = proto.Field( + proto.STRING, + number=2, + ) + owner: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ReleaseLeaseResponse(proto.Message): + r"""Response message for release lease. + """ + + +class RequestMetadata(proto.Message): + r"""RequestMetadata is the metadata message for the request. + + Attributes: + stream (str): + Stream name. + event (str): + Evevt name. + series (str): + Series name. + lease_id (str): + Lease id. + owner (str): + Owner name. + lease_term (google.protobuf.duration_pb2.Duration): + Lease term specifies how long the client + wants the session to be maintained by the server + after the client leaves. If the lease term is + not set, the server will release the session + immediately and the client cannot reconnect to + the same session later. + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + event: str = proto.Field( + proto.STRING, + number=2, + ) + series: str = proto.Field( + proto.STRING, + number=3, + ) + lease_id: str = proto.Field( + proto.STRING, + number=4, + ) + owner: str = proto.Field( + proto.STRING, + number=5, + ) + lease_term: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + +class SendPacketsRequest(proto.Message): + r"""Request message for sending packets. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + packet (google.cloud.visionai_v1.types.Packet): + Packets sent over the streaming rpc. + + This field is a member of `oneof`_ ``request``. + metadata (google.cloud.visionai_v1.types.RequestMetadata): + The first message of the streaming rpc + including the request metadata. + + This field is a member of `oneof`_ ``request``. + """ + + packet: streaming_resources.Packet = proto.Field( + proto.MESSAGE, + number=1, + oneof='request', + message=streaming_resources.Packet, + ) + metadata: 'RequestMetadata' = proto.Field( + proto.MESSAGE, + number=2, + oneof='request', + message='RequestMetadata', + ) + + +class SendPacketsResponse(proto.Message): + r"""Response message for sending packets. + """ + + +class ReceivePacketsRequest(proto.Message): + r"""Request message for receiving packets. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + setup_request (google.cloud.visionai_v1.types.ReceivePacketsRequest.SetupRequest): + The request to setup the initial state of + session. + The client must send and only send this as the + first message. + + This field is a member of `oneof`_ ``request``. + commit_request (google.cloud.visionai_v1.types.CommitRequest): + This request checkpoints the consumer's read + progress. + + This field is a member of `oneof`_ ``request``. + """ + + class SetupRequest(proto.Message): + r"""The message specifying the initial settings for the + ReceivePackets session. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + eager_receive_mode (google.cloud.visionai_v1.types.EagerMode): + Options for configuring eager mode. + + This field is a member of `oneof`_ ``consumer_mode``. + controlled_receive_mode (google.cloud.visionai_v1.types.ControlledMode): + Options for configuring controlled mode. + + This field is a member of `oneof`_ ``consumer_mode``. + metadata (google.cloud.visionai_v1.types.RequestMetadata): + The configurations that specify where packets + are retrieved. + receiver (str): + A name for the receiver to self-identify. + + This is used to keep track of a receiver's read + progress. + heartbeat_interval (google.protobuf.duration_pb2.Duration): + The maximum duration of server silence before the client + determines the server unreachable. + + The client must either receive a ``Packet`` or a heart beat + message before this duration expires; otherwise, the client + will automatically cancel the current connection and retry. + writes_done_grace_period (google.protobuf.duration_pb2.Duration): + The grace period after which a ``writes_done_request`` is + issued, that a ``WritesDone`` is expected from the client. + + The server is free to cancel the RPC should this expire. + + A system default will be chosen if unset. + """ + + eager_receive_mode: 'EagerMode' = proto.Field( + proto.MESSAGE, + number=3, + oneof='consumer_mode', + message='EagerMode', + ) + controlled_receive_mode: 'ControlledMode' = proto.Field( + proto.MESSAGE, + number=4, + oneof='consumer_mode', + message='ControlledMode', + ) + metadata: 'RequestMetadata' = proto.Field( + proto.MESSAGE, + number=1, + message='RequestMetadata', + ) + receiver: str = proto.Field( + proto.STRING, + number=2, + ) + heartbeat_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + writes_done_grace_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + setup_request: SetupRequest = proto.Field( + proto.MESSAGE, + number=6, + oneof='request', + message=SetupRequest, + ) + commit_request: 'CommitRequest' = proto.Field( + proto.MESSAGE, + number=7, + oneof='request', + message='CommitRequest', + ) + + +class ReceivePacketsControlResponse(proto.Message): + r"""Control message for a ReceivePacketsResponse. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + heartbeat (bool): + A server heartbeat. + + This field is a member of `oneof`_ ``control``. + writes_done_request (bool): + A request to the receiver to complete any final writes + followed by a ``WritesDone``; e.g. issue any final + ``CommitRequest``\ s. + + May be ignored if ``WritesDone`` has already been issued at + any point prior to receiving this message. + + If ``WritesDone`` does not get issued, then the server will + forcefully cancel the connection, and the receiver will + likely receive an uninformative after ``Read`` returns + ``false`` and ``Finish`` is called. + + This field is a member of `oneof`_ ``control``. + """ + + heartbeat: bool = proto.Field( + proto.BOOL, + number=1, + oneof='control', + ) + writes_done_request: bool = proto.Field( + proto.BOOL, + number=2, + oneof='control', + ) + + +class ReceivePacketsResponse(proto.Message): + r"""Response message from ReceivePackets. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + packet (google.cloud.visionai_v1.types.Packet): + A genuine data payload originating from the + sender. + + This field is a member of `oneof`_ ``response``. + control (google.cloud.visionai_v1.types.ReceivePacketsControlResponse): + A control message from the server. + + This field is a member of `oneof`_ ``response``. + """ + + packet: streaming_resources.Packet = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message=streaming_resources.Packet, + ) + control: 'ReceivePacketsControlResponse' = proto.Field( + proto.MESSAGE, + number=3, + oneof='response', + message='ReceivePacketsControlResponse', + ) + + +class EagerMode(proto.Message): + r"""The options for receiver under the eager mode. + """ + + +class ControlledMode(proto.Message): + r"""The options for receiver under the controlled mode. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + starting_logical_offset (str): + This can be set to the following logical + starting points: + "begin": This will read from the earliest + available message. + + "most-recent": This will read from the latest + available message. + + "end": This will read only future messages. + + "stored": This will resume reads one past the + last committed offset. It is the only + option that resumes progress; all others + jump unilaterally. + + This field is a member of `oneof`_ ``starting_offset``. + fallback_starting_offset (str): + This is the logical starting point to + fallback upon should the specified starting + offset be unavailable. + + This can be one of the following values: + + "begin": This will read from the earliest + available message. + + "end": This will read only future messages. + """ + + starting_logical_offset: str = proto.Field( + proto.STRING, + number=1, + oneof='starting_offset', + ) + fallback_starting_offset: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CommitRequest(proto.Message): + r"""The message for explicitly committing the read progress. + + This may only be used when ``ReceivePacketsControlledMode`` is set + in the initial setup request. + + Attributes: + offset (int): + The offset to commit. + """ + + offset: int = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streams_resources.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streams_resources.py new file mode 100644 index 000000000000..0bdc55f359d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streams_resources.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'Stream', + 'Event', + 'Series', + 'Channel', + }, +) + + +class Stream(proto.Message): + r"""Message describing the Stream object. The Stream and the + Event resources are many to many; i.e., each Stream resource can + associate to many Event resources and each Event resource can + associate to many Stream resources. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + display_name (str): + The display name for the stream resource. + enable_hls_playback (bool): + Whether to enable the HLS playback service on + this stream. + media_warehouse_asset (str): + The name of the media warehouse asset for long term storage + of stream data. Format: + projects/${p_id}/locations/${l_id}/corpora/${c_id}/assets/${a_id} + Remain empty if the media warehouse storage is not needed + for the stream. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + enable_hls_playback: bool = proto.Field( + proto.BOOL, + number=7, + ) + media_warehouse_asset: str = proto.Field( + proto.STRING, + number=8, + ) + + +class Event(proto.Message): + r"""Message describing the Event object. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + alignment_clock (google.cloud.visionai_v1.types.Event.Clock): + The clock used for joining streams. + grace_period (google.protobuf.duration_pb2.Duration): + Grace period for cleaning up the event. This is the time the + controller waits for before deleting the event. During this + period, if there is any active channel on the event. The + deletion of the event after grace_period will be ignored. + """ + class Clock(proto.Enum): + r"""Clock that will be used for joining streams. + + Values: + CLOCK_UNSPECIFIED (0): + Clock is not specified. + CAPTURE (1): + Use the timestamp when the data is captured. + Clients need to sync the clock. + INGEST (2): + Use the timestamp when the data is received. + """ + CLOCK_UNSPECIFIED = 0 + CAPTURE = 1 + INGEST = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + alignment_clock: Clock = proto.Field( + proto.ENUM, + number=6, + enum=Clock, + ) + grace_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + + +class Series(proto.Message): + r"""Message describing the Series object. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + stream (str): + Required. Stream that is associated with this + series. + event (str): + Required. Event that is associated with this + series. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + stream: str = proto.Field( + proto.STRING, + number=6, + ) + event: str = proto.Field( + proto.STRING, + number=7, + ) + + +class Channel(proto.Message): + r"""Message describing the Channel object. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + stream (str): + Required. Stream that is associated with this + series. + event (str): + Required. Event that is associated with this + series. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + stream: str = proto.Field( + proto.STRING, + number=6, + ) + event: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streams_service.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streams_service.py new file mode 100644 index 000000000000..470adbd94a28 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/streams_service.py @@ -0,0 +1,1130 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'ListClustersRequest', + 'ListClustersResponse', + 'GetClusterRequest', + 'CreateClusterRequest', + 'UpdateClusterRequest', + 'DeleteClusterRequest', + 'ListStreamsRequest', + 'ListStreamsResponse', + 'GetStreamRequest', + 'CreateStreamRequest', + 'UpdateStreamRequest', + 'DeleteStreamRequest', + 'GetStreamThumbnailRequest', + 'GetStreamThumbnailResponse', + 'GenerateStreamHlsTokenRequest', + 'GenerateStreamHlsTokenResponse', + 'ListEventsRequest', + 'ListEventsResponse', + 'GetEventRequest', + 'CreateEventRequest', + 'UpdateEventRequest', + 'DeleteEventRequest', + 'ListSeriesRequest', + 'ListSeriesResponse', + 'GetSeriesRequest', + 'CreateSeriesRequest', + 'UpdateSeriesRequest', + 'DeleteSeriesRequest', + 'MaterializeChannelRequest', + }, +) + + +class ListClustersRequest(proto.Message): + r"""Message for requesting list of Clusters. + + Attributes: + parent (str): + Required. Parent value for + ListClustersRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListClustersResponse(proto.Message): + r"""Message for response to listing Clusters. + + Attributes: + clusters (MutableSequence[google.cloud.visionai_v1.types.Cluster]): + The list of Cluster. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + clusters: MutableSequence[common.Cluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=common.Cluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetClusterRequest(proto.Message): + r"""Message for getting a Cluster. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateClusterRequest(proto.Message): + r"""Message for creating a Cluster. + + Attributes: + parent (str): + Required. Value for parent. + cluster_id (str): + Required. Id of the requesting object. + cluster (google.cloud.visionai_v1.types.Cluster): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: common.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=common.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateClusterRequest(proto.Message): + r"""Message for updating a Cluster. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + cluster (google.cloud.visionai_v1.types.Cluster): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + cluster: common.Cluster = proto.Field( + proto.MESSAGE, + number=2, + message=common.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteClusterRequest(proto.Message): + r"""Message for deleting a Cluster. + + Attributes: + name (str): + Required. Name of the resource + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListStreamsRequest(proto.Message): + r"""Message for requesting list of Streams. + + Attributes: + parent (str): + Required. Parent value for + ListStreamsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListStreamsResponse(proto.Message): + r"""Message for response to listing Streams. + + Attributes: + streams (MutableSequence[google.cloud.visionai_v1.types.Stream]): + The list of Stream. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + streams: MutableSequence[streams_resources.Stream] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=streams_resources.Stream, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetStreamRequest(proto.Message): + r"""Message for getting a Stream. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateStreamRequest(proto.Message): + r"""Message for creating a Stream. + + Attributes: + parent (str): + Required. Value for parent. + stream_id (str): + Required. Id of the requesting object. + stream (google.cloud.visionai_v1.types.Stream): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + stream_id: str = proto.Field( + proto.STRING, + number=2, + ) + stream: streams_resources.Stream = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Stream, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateStreamRequest(proto.Message): + r"""Message for updating a Stream. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Stream resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + stream (google.cloud.visionai_v1.types.Stream): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + stream: streams_resources.Stream = proto.Field( + proto.MESSAGE, + number=2, + message=streams_resources.Stream, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteStreamRequest(proto.Message): + r"""Message for deleting a Stream. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetStreamThumbnailRequest(proto.Message): + r"""Message for getting the thumbnail of a Stream. + + Attributes: + stream (str): + Required. The name of the stream for to get + the thumbnail from. + gcs_object_name (str): + Required. The name of the GCS object to store + the thumbnail image. + event (str): + Optional. The name of the event. If + unspecified, the thumbnail will be retrieved + from the latest event. + request_id (str): + Optional. An optional request ID to identify + the requests. Specify a unique request ID so + that if you must retry your request, the server + will know to ignore the request if it has + already been completed. The server will + guarantee that for at least 60 minutes since the + first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + gcs_object_name: str = proto.Field( + proto.STRING, + number=2, + ) + event: str = proto.Field( + proto.STRING, + number=3, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetStreamThumbnailResponse(proto.Message): + r"""Message for the response of GetStreamThumbnail. The empty + response message indicates the thumbnail image has been uploaded + to GCS successfully. + + """ + + +class GenerateStreamHlsTokenRequest(proto.Message): + r"""Request message for getting the auth token to access the + stream HLS contents. + + Attributes: + stream (str): + Required. The name of the stream. + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateStreamHlsTokenResponse(proto.Message): + r"""Response message for GenerateStreamHlsToken. + + Attributes: + token (str): + The generated JWT token. + + The caller should insert this token to the + authorization header of the HTTP requests to get + the HLS playlist manifest and the video chunks. + eg: curl -H "Authorization: Bearer $TOKEN" + https://domain.com/test-stream.playback/master.m3u8 + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + The expiration time of the token. + """ + + token: str = proto.Field( + proto.STRING, + number=1, + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListEventsRequest(proto.Message): + r"""Message for requesting list of Events. + + Attributes: + parent (str): + Required. Parent value for ListEventsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEventsResponse(proto.Message): + r"""Message for response to listing Events. + + Attributes: + events (MutableSequence[google.cloud.visionai_v1.types.Event]): + The list of Event. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + events: MutableSequence[streams_resources.Event] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=streams_resources.Event, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetEventRequest(proto.Message): + r"""Message for getting a Event. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEventRequest(proto.Message): + r"""Message for creating a Event. + + Attributes: + parent (str): + Required. Value for parent. + event_id (str): + Required. Id of the requesting object. + event (google.cloud.visionai_v1.types.Event): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_id: str = proto.Field( + proto.STRING, + number=2, + ) + event: streams_resources.Event = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Event, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateEventRequest(proto.Message): + r"""Message for updating a Event. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Event resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + event (google.cloud.visionai_v1.types.Event): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + event: streams_resources.Event = proto.Field( + proto.MESSAGE, + number=2, + message=streams_resources.Event, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteEventRequest(proto.Message): + r"""Message for deleting a Event. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSeriesRequest(proto.Message): + r"""Message for requesting list of Series. + + Attributes: + parent (str): + Required. Parent value for ListSeriesRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSeriesResponse(proto.Message): + r"""Message for response to listing Series. + + Attributes: + series (MutableSequence[google.cloud.visionai_v1.types.Series]): + The list of Series. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + series: MutableSequence[streams_resources.Series] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=streams_resources.Series, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetSeriesRequest(proto.Message): + r"""Message for getting a Series. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSeriesRequest(proto.Message): + r"""Message for creating a Series. + + Attributes: + parent (str): + Required. Value for parent. + series_id (str): + Required. Id of the requesting object. + series (google.cloud.visionai_v1.types.Series): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + series_id: str = proto.Field( + proto.STRING, + number=2, + ) + series: streams_resources.Series = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Series, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateSeriesRequest(proto.Message): + r"""Message for updating a Series. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Series resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + series (google.cloud.visionai_v1.types.Series): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + series: streams_resources.Series = proto.Field( + proto.MESSAGE, + number=2, + message=streams_resources.Series, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteSeriesRequest(proto.Message): + r"""Message for deleting a Series. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MaterializeChannelRequest(proto.Message): + r"""Message for materializing a channel. + + Attributes: + parent (str): + Required. Value for parent. + channel_id (str): + Required. Id of the channel. + channel (google.cloud.visionai_v1.types.Channel): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + channel_id: str = proto.Field( + proto.STRING, + number=2, + ) + channel: streams_resources.Channel = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Channel, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/warehouse.py b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/warehouse.py new file mode 100644 index 000000000000..f159a1a8678b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/google/cloud/visionai_v1/types/warehouse.py @@ -0,0 +1,5144 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1.types import common +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1', + manifest={ + 'FacetBucketType', + 'CreateAssetRequest', + 'GetAssetRequest', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'UpdateAssetRequest', + 'DeleteAssetRequest', + 'AssetSource', + 'UploadAssetRequest', + 'UploadAssetResponse', + 'UploadAssetMetadata', + 'GenerateRetrievalUrlRequest', + 'GenerateRetrievalUrlResponse', + 'Asset', + 'AnalyzeAssetRequest', + 'AnalyzeAssetMetadata', + 'AnalyzeAssetResponse', + 'IndexingStatus', + 'IndexAssetRequest', + 'IndexAssetMetadata', + 'IndexAssetResponse', + 'RemoveIndexAssetRequest', + 'RemoveIndexAssetMetadata', + 'RemoveIndexAssetResponse', + 'IndexedAsset', + 'ViewIndexedAssetsRequest', + 'ViewIndexedAssetsResponse', + 'CreateCorpusRequest', + 'CreateCorpusMetadata', + 'SearchCapability', + 'SearchCapabilitySetting', + 'CreateCollectionMetadata', + 'CreateCollectionRequest', + 'DeleteCollectionMetadata', + 'DeleteCollectionRequest', + 'GetCollectionRequest', + 'UpdateCollectionRequest', + 'ListCollectionsRequest', + 'ListCollectionsResponse', + 'AddCollectionItemRequest', + 'AddCollectionItemResponse', + 'RemoveCollectionItemRequest', + 'RemoveCollectionItemResponse', + 'ViewCollectionItemsRequest', + 'ViewCollectionItemsResponse', + 'Collection', + 'CollectionItem', + 'CreateIndexRequest', + 'CreateIndexMetadata', + 'UpdateIndexRequest', + 'UpdateIndexMetadata', + 'GetIndexRequest', + 'ListIndexesRequest', + 'ListIndexesResponse', + 'DeleteIndexRequest', + 'DeleteIndexMetadata', + 'Index', + 'DeployedIndexReference', + 'Corpus', + 'GetCorpusRequest', + 'UpdateCorpusRequest', + 'ListCorporaRequest', + 'ListCorporaResponse', + 'DeleteCorpusRequest', + 'AnalyzeCorpusRequest', + 'AnalyzeCorpusMetadata', + 'AnalyzeCorpusResponse', + 'CreateDataSchemaRequest', + 'DataSchema', + 'DataSchemaDetails', + 'UpdateDataSchemaRequest', + 'GetDataSchemaRequest', + 'DeleteDataSchemaRequest', + 'ListDataSchemasRequest', + 'ListDataSchemasResponse', + 'CreateAnnotationRequest', + 'Annotation', + 'UserSpecifiedAnnotation', + 'GeoCoordinate', + 'AnnotationValue', + 'AnnotationList', + 'AnnotationCustomizedStruct', + 'ListAnnotationsRequest', + 'ListAnnotationsResponse', + 'GetAnnotationRequest', + 'UpdateAnnotationRequest', + 'DeleteAnnotationRequest', + 'ImportAssetsRequest', + 'ImportAssetsMetadata', + 'ImportAssetsResponse', + 'CreateSearchConfigRequest', + 'UpdateSearchConfigRequest', + 'GetSearchConfigRequest', + 'DeleteSearchConfigRequest', + 'ListSearchConfigsRequest', + 'ListSearchConfigsResponse', + 'SearchConfig', + 'IndexEndpoint', + 'CreateIndexEndpointRequest', + 'CreateIndexEndpointMetadata', + 'GetIndexEndpointRequest', + 'ListIndexEndpointsRequest', + 'ListIndexEndpointsResponse', + 'UpdateIndexEndpointRequest', + 'UpdateIndexEndpointMetadata', + 'DeleteIndexEndpointRequest', + 'DeleteIndexEndpointMetadata', + 'DeployIndexRequest', + 'DeployIndexResponse', + 'DeployIndexMetadata', + 'UndeployIndexMetadata', + 'UndeployIndexRequest', + 'UndeployIndexResponse', + 'DeployedIndex', + 'FacetProperty', + 'SearchHypernym', + 'CreateSearchHypernymRequest', + 'UpdateSearchHypernymRequest', + 'GetSearchHypernymRequest', + 'DeleteSearchHypernymRequest', + 'ListSearchHypernymsRequest', + 'ListSearchHypernymsResponse', + 'SearchCriteriaProperty', + 'FacetValue', + 'FacetBucket', + 'FacetGroup', + 'IngestAssetRequest', + 'IngestAssetResponse', + 'ClipAssetRequest', + 'ClipAssetResponse', + 'GenerateHlsUriRequest', + 'GenerateHlsUriResponse', + 'SearchAssetsRequest', + 'SearchIndexEndpointRequest', + 'ImageQuery', + 'SchemaKeySortingStrategy', + 'DeleteAssetMetadata', + 'AnnotationMatchingResult', + 'SearchResultItem', + 'SearchAssetsResponse', + 'SearchIndexEndpointResponse', + 'IntRange', + 'FloatRange', + 'StringArray', + 'IntRangeArray', + 'FloatRangeArray', + 'DateTimeRange', + 'DateTimeRangeArray', + 'CircleArea', + 'GeoLocationArray', + 'BoolValue', + 'Criteria', + 'Partition', + }, +) + + +class FacetBucketType(proto.Enum): + r"""Different types for a facet bucket. + + Values: + FACET_BUCKET_TYPE_UNSPECIFIED (0): + Unspecified type. + FACET_BUCKET_TYPE_VALUE (1): + Value type. + FACET_BUCKET_TYPE_DATETIME (2): + Datetime type. + FACET_BUCKET_TYPE_FIXED_RANGE (3): + Fixed Range type. + FACET_BUCKET_TYPE_CUSTOM_RANGE (4): + Custom Range type. + """ + FACET_BUCKET_TYPE_UNSPECIFIED = 0 + FACET_BUCKET_TYPE_VALUE = 1 + FACET_BUCKET_TYPE_DATETIME = 2 + FACET_BUCKET_TYPE_FIXED_RANGE = 3 + FACET_BUCKET_TYPE_CUSTOM_RANGE = 4 + + +class CreateAssetRequest(proto.Message): + r"""Request message for CreateAssetRequest. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource where this asset will be + created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + asset (google.cloud.visionai_v1.types.Asset): + Required. The asset to create. + asset_id (str): + Optional. The ID to use for the asset, which will become the + final component of the asset's resource name if user choose + to specify. Otherwise, asset id will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must be a + letter, the last could be a letter or a number. + + This field is a member of `oneof`_ ``_asset_id``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + asset: 'Asset' = proto.Field( + proto.MESSAGE, + number=2, + message='Asset', + ) + asset_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class GetAssetRequest(proto.Message): + r"""Request message for GetAsset. + + Attributes: + name (str): + Required. The name of the asset to retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for ListAssets. + + Attributes: + parent (str): + Required. The parent, which owns this collection of assets. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + page_size (int): + The maximum number of assets to return. The + service may return fewer than this value. + If unspecified, at most 50 assets will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListAssets`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListAssets`` must match the call that provided the page + token. + filter (str): + The filter applied to the returned list. Only the following + filterings are supported: "assets_with_contents = true", + which returns assets with contents uploaded; + "assets_with_contents = false", which returns assets without + contents. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for ListAssets. + + Attributes: + assets (MutableSequence[google.cloud.visionai_v1.types.Asset]): + The assets from the specified corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + assets: MutableSequence['Asset'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Asset', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateAssetRequest(proto.Message): + r"""Request message for UpdateAsset. + + Attributes: + asset (google.cloud.visionai_v1.types.Asset): + Required. The asset to update. + + The asset's ``name`` field is used to identify the asset to + be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + asset: 'Asset' = proto.Field( + proto.MESSAGE, + number=1, + message='Asset', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAssetRequest(proto.Message): + r"""Request message for DeleteAsset. + + Attributes: + name (str): + Required. The name of the asset to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AssetSource(proto.Message): + r"""The source of the asset. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + asset_gcs_source (google.cloud.visionai_v1.types.AssetSource.AssetGcsSource): + The source of the asset is from Cloud + Storage. + + This field is a member of `oneof`_ ``source_form``. + asset_content_data (google.cloud.visionai_v1.types.AssetSource.AssetContentData): + The source of the asset is from content + bytes. + + This field is a member of `oneof`_ ``source_form``. + """ + + class AssetGcsSource(proto.Message): + r"""The asset source is from Cloud Storage. + + Attributes: + gcs_uri (str): + Cloud storage uri. + """ + + gcs_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class AssetContentData(proto.Message): + r"""The content of the asset. + + Attributes: + asset_content_data (bytes): + + """ + + asset_content_data: bytes = proto.Field( + proto.BYTES, + number=1, + ) + + asset_gcs_source: AssetGcsSource = proto.Field( + proto.MESSAGE, + number=1, + oneof='source_form', + message=AssetGcsSource, + ) + asset_content_data: AssetContentData = proto.Field( + proto.MESSAGE, + number=2, + oneof='source_form', + message=AssetContentData, + ) + + +class UploadAssetRequest(proto.Message): + r"""Request message for UploadAsset. + + Attributes: + name (str): + Required. The resource name of the asset to upload. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + asset_source (google.cloud.visionai_v1.types.AssetSource): + The source of the asset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_source: 'AssetSource' = proto.Field( + proto.MESSAGE, + number=2, + message='AssetSource', + ) + + +class UploadAssetResponse(proto.Message): + r"""Response message for UploadAsset. + """ + + +class UploadAssetMetadata(proto.Message): + r"""Metadata for UploadAsset. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The update time of the operation. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GenerateRetrievalUrlRequest(proto.Message): + r"""Request message for GenerateRetrievalUrl API. + + Attributes: + name (str): + Required. The resource name of the asset to request signed + url for. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateRetrievalUrlResponse(proto.Message): + r"""Response message for GenerateRetrievalUrl API. + + Attributes: + signed_uri (str): + A signed url to download the content of the + asset. + """ + + signed_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Asset(proto.Message): + r"""An asset is a resource in corpus. It represents a media + object inside corpus, contains metadata and another resource + annotation. Different feature could be applied to the asset to + generate annotations. User could specified annotation related to + the target asset. + + Attributes: + name (str): + Resource name of the asset. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + ttl (google.protobuf.duration_pb2.Duration): + The duration for which all media assets, + associated metadata, and search documents can + exist. If not set, then it will using the + default ttl in the parent corpus resource. + asset_gcs_source (google.cloud.visionai_v1.types.AssetSource.AssetGcsSource): + Output only. The original cloud storage + source uri that is associated with this asset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + asset_gcs_source: 'AssetSource.AssetGcsSource' = proto.Field( + proto.MESSAGE, + number=4, + message='AssetSource.AssetGcsSource', + ) + + +class AnalyzeAssetRequest(proto.Message): + r"""Request message for AnalyzeAsset. + + Attributes: + name (str): + Required. The resource name of the asset to analyze. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AnalyzeAssetMetadata(proto.Message): + r"""Metadata for AnalyzeAsset. + + Attributes: + analysis_status (MutableSequence[google.cloud.visionai_v1.types.AnalyzeAssetMetadata.AnalysisStatus]): + The status of analysis on all search + capabilities. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The update time of the operation. + """ + + class AnalysisStatus(proto.Message): + r"""The status of analysis on each search capability. + + Attributes: + state (google.cloud.visionai_v1.types.AnalyzeAssetMetadata.AnalysisStatus.State): + + status_message (str): + + search_capability (google.cloud.visionai_v1.types.SearchCapability): + The search capability requested. + """ + class State(proto.Enum): + r"""The state of the search capability. + + Values: + STATE_UNSPECIFIED (0): + The default process state should never + happen. + IN_PROGRESS (1): + The feature is in progress. + SUCCEEDED (2): + The process is successfully done. + FAILED (3): + The process failed. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + SUCCEEDED = 2 + FAILED = 3 + + state: 'AnalyzeAssetMetadata.AnalysisStatus.State' = proto.Field( + proto.ENUM, + number=2, + enum='AnalyzeAssetMetadata.AnalysisStatus.State', + ) + status_message: str = proto.Field( + proto.STRING, + number=3, + ) + search_capability: 'SearchCapability' = proto.Field( + proto.MESSAGE, + number=4, + message='SearchCapability', + ) + + analysis_status: MutableSequence[AnalysisStatus] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AnalysisStatus, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class AnalyzeAssetResponse(proto.Message): + r"""Response message for AnalyzeAsset. + """ + + +class IndexingStatus(proto.Message): + r"""The status of indexing for the asset. + + Attributes: + state (google.cloud.visionai_v1.types.IndexingStatus.State): + Output only. State of this asset's indexing. + status_message (str): + Detailed message describing the state. + """ + class State(proto.Enum): + r"""State enum for this asset's indexing. + + Values: + STATE_UNSPECIFIED (0): + The default process state should never + happen. + IN_PROGRESS (1): + The indexing is in progress. + SUCCEEDED (2): + The process is successfully done. + FAILED (3): + The process failed. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + SUCCEEDED = 2 + FAILED = 3 + + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + status_message: str = proto.Field( + proto.STRING, + number=3, + ) + + +class IndexAssetRequest(proto.Message): + r"""Request message for IndexAsset. + + Attributes: + name (str): + Required. The resource name of the asset to index. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + index (str): + Optional. The name of the index. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + index: str = proto.Field( + proto.STRING, + number=2, + ) + + +class IndexAssetMetadata(proto.Message): + r"""Metadata for IndexAsset. + + Attributes: + status (google.cloud.visionai_v1.types.IndexingStatus): + The status of indexing this asset. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The update time of the operation. + """ + + status: 'IndexingStatus' = proto.Field( + proto.MESSAGE, + number=4, + message='IndexingStatus', + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class IndexAssetResponse(proto.Message): + r"""Response message for IndexAsset. + """ + + +class RemoveIndexAssetRequest(proto.Message): + r"""Request message for RemoveIndexAsset. + + Attributes: + name (str): + Required. The resource name of the asset to index. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + index (str): + Optional. The name of the index. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + index: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RemoveIndexAssetMetadata(proto.Message): + r"""Metadata for RemoveIndexAsset. + + Attributes: + indexing_status (google.cloud.visionai_v1.types.IndexingStatus): + The status of indexing this asset. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The update time of the operation. + """ + + indexing_status: 'IndexingStatus' = proto.Field( + proto.MESSAGE, + number=1, + message='IndexingStatus', + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RemoveIndexAssetResponse(proto.Message): + r"""Response message for RemoveIndexAsset. + """ + + +class IndexedAsset(proto.Message): + r"""An IndexedAsset is an asset that the index is built upon. + + Attributes: + index (str): + Required. The index that this indexed asset belongs to. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + asset (str): + Required. The resource name of the asset. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + """ + + index: str = proto.Field( + proto.STRING, + number=1, + ) + asset: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class ViewIndexedAssetsRequest(proto.Message): + r"""Request message for ViewIndexedAssets. + + Attributes: + index (str): + Required. The index that owns this collection of assets. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + page_size (int): + The maximum number of assets to return. The + service may return fewer than this value. + If unspecified, at most 50 assets will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ViewIndexedAssets`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ViewIndexedAssets`` must match the call that provided the + page token. + filter (str): + The filter applied to the returned list. Only the following + filterings are supported: "asset_id = xxxx", which returns + asset with specified id. "asset_id = xxxx, yyyy, zzzz", + which returns assets with specified ids. + """ + + index: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ViewIndexedAssetsResponse(proto.Message): + r"""Response message for ViewIndexedAssets. + + Attributes: + indexed_assets (MutableSequence[google.cloud.visionai_v1.types.IndexedAsset]): + The assets from the specified index. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + indexed_assets: MutableSequence['IndexedAsset'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IndexedAsset', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateCorpusRequest(proto.Message): + r"""Request message of CreateCorpus API. + + Attributes: + parent (str): + Required. Form: + ``projects/{project_number}/locations/{location_id}`` + corpus (google.cloud.visionai_v1.types.Corpus): + Required. The corpus to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + corpus: 'Corpus' = proto.Field( + proto.MESSAGE, + number=2, + message='Corpus', + ) + + +class CreateCorpusMetadata(proto.Message): + r"""Metadata for CreateCorpus API. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The create time of the create corpus + operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The update time of the create corpus + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class SearchCapability(proto.Message): + r"""The capability and metadata of search capability. + + Attributes: + type_ (google.cloud.visionai_v1.types.SearchCapability.Type): + The search capability to enable. + """ + class Type(proto.Enum): + r"""Capability to perform different search on assets. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified search capability, should never + be used. + EMBEDDING_SEARCH (1): + Embedding search. + """ + TYPE_UNSPECIFIED = 0 + EMBEDDING_SEARCH = 1 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + + +class SearchCapabilitySetting(proto.Message): + r"""Setting for search capability to enable. + + Attributes: + search_capabilities (MutableSequence[google.cloud.visionai_v1.types.SearchCapability]): + The metadata of search capability to enable. + """ + + search_capabilities: MutableSequence['SearchCapability'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchCapability', + ) + + +class CreateCollectionMetadata(proto.Message): + r"""Metadata message for CreateCollectionRequest + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class CreateCollectionRequest(proto.Message): + r"""Request message for CreateCollection. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource where this collection will be + created. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + collection (google.cloud.visionai_v1.types.Collection): + Required. The collection resource to be + created. + collection_id (str): + Optional. The ID to use for the collection, which will + become the final component of the resource name if user + choose to specify. Otherwise, collection id will be + generated by system. + + This value should be up to 55 characters, and valid + characters are /[a-z][0-9]-/. The first character must be a + letter, the last could be a letter or a number. + + This field is a member of `oneof`_ ``_collection_id``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + collection: 'Collection' = proto.Field( + proto.MESSAGE, + number=2, + message='Collection', + ) + collection_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class DeleteCollectionMetadata(proto.Message): + r"""Metadata message for DeleteCollectionRequest + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class DeleteCollectionRequest(proto.Message): + r"""Request message for DeleteCollectionRequest. + + Attributes: + name (str): + Required. The name of the collection to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCollectionRequest(proto.Message): + r"""Request message for GetCollectionRequest. + + Attributes: + name (str): + Required. The name of the collection to retrieve. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCollectionRequest(proto.Message): + r"""Request message for UpdateCollectionRequest. + + Attributes: + collection (google.cloud.visionai_v1.types.Collection): + Required. The collection to update. + + The collection's ``name`` field is used to identify the + collection to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + + - Unset ``update_mask`` or set ``update_mask`` to be a + single "*" only will update all updatable fields with the + value provided in ``collection``. + - To update ``display_name`` value to empty string, set it + in the ``collection`` to empty string, and set + ``update_mask`` with "display_name". Same applies to + other updatable string fields in the ``collection``. + """ + + collection: 'Collection' = proto.Field( + proto.MESSAGE, + number=1, + message='Collection', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListCollectionsRequest(proto.Message): + r"""Request message for ListCollections. + + Attributes: + parent (str): + Required. The parent corpus. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + page_size (int): + The maximum number of collections to return. + The service may return fewer than this value. If + unspecified, at most 50 collections will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListCollectionsRequest`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListCollectionsRequest`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCollectionsResponse(proto.Message): + r"""Response message for ListCollections. + + Attributes: + collections (MutableSequence[google.cloud.visionai_v1.types.Collection]): + The collections from the specified corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + collections: MutableSequence['Collection'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Collection', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AddCollectionItemRequest(proto.Message): + r"""Request message for AddCollectionItem. + + Attributes: + item (google.cloud.visionai_v1.types.CollectionItem): + Required. The item to be added. + """ + + item: 'CollectionItem' = proto.Field( + proto.MESSAGE, + number=1, + message='CollectionItem', + ) + + +class AddCollectionItemResponse(proto.Message): + r"""Response message for AddCollectionItem. + + Attributes: + item (google.cloud.visionai_v1.types.CollectionItem): + The item that has already been added. + """ + + item: 'CollectionItem' = proto.Field( + proto.MESSAGE, + number=1, + message='CollectionItem', + ) + + +class RemoveCollectionItemRequest(proto.Message): + r"""Request message for RemoveCollectionItem. + + Attributes: + item (google.cloud.visionai_v1.types.CollectionItem): + Required. The item to be removed. + """ + + item: 'CollectionItem' = proto.Field( + proto.MESSAGE, + number=1, + message='CollectionItem', + ) + + +class RemoveCollectionItemResponse(proto.Message): + r"""Request message for RemoveCollectionItem. + + Attributes: + item (google.cloud.visionai_v1.types.CollectionItem): + The item that has already been removed. + """ + + item: 'CollectionItem' = proto.Field( + proto.MESSAGE, + number=1, + message='CollectionItem', + ) + + +class ViewCollectionItemsRequest(proto.Message): + r"""Request message for ViewCollectionItems. + + Attributes: + collection (str): + Required. The collection to view. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + page_size (int): + The maximum number of collections to return. + The service may return fewer than this value. If + unspecified, at most 50 collections will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ViewCollectionItemsRequest`` call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ViewCollectionItemsRequest`` must match the call that + provided the page token. + """ + + collection: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ViewCollectionItemsResponse(proto.Message): + r"""Response message for ViewCollectionItems. + + Attributes: + items (MutableSequence[google.cloud.visionai_v1.types.CollectionItem]): + The items from the specified collection. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + items: MutableSequence['CollectionItem'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CollectionItem', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Collection(proto.Message): + r"""A collection is a resource in a corpus. It serves as a + container of references to original resources. + + Attributes: + name (str): + Output only. Resource name of the collection. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + display_name (str): + Optional. The collection name for displaying. + The name can be up to 256 characters long. + description (str): + Optional. Description of the collection. Can + be up to 25000 characters long. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CollectionItem(proto.Message): + r"""A CollectionItem is an item in a collection. + Each item is a reference to the original resource in a + collection. + + Attributes: + collection (str): + Required. The collection name that this item belongs to. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}`` + type_ (google.cloud.visionai_v1.types.CollectionItem.Type): + Required. The type of item. + item_resource (str): + Required. The name of the CollectionItem. Its format depends + on the ``type`` above. For ASSET: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + """ + class Type(proto.Enum): + r"""CollectionItem types. + + Values: + TYPE_UNSPECIFIED (0): + The default type of item should never happen. + ASSET (1): + Asset type item. + """ + TYPE_UNSPECIFIED = 0 + ASSET = 1 + + collection: str = proto.Field( + proto.STRING, + number=1, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + item_resource: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateIndexRequest(proto.Message): + r"""Message for creating an Index. + + Attributes: + parent (str): + Required. Value for the parent. The resource name of the + Corpus under which this index is created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + index_id (str): + Optional. The ID for the index. This will become the final + resource name for the index. If the user does not specify + this value, it will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must be a + letter, the last could be a letter or a number. + index (google.cloud.visionai_v1.types.Index): + Required. The index being created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + index_id: str = proto.Field( + proto.STRING, + number=2, + ) + index: 'Index' = proto.Field( + proto.MESSAGE, + number=3, + message='Index', + ) + + +class CreateIndexMetadata(proto.Message): + r"""Metadata message for CreateIndexRequest + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class UpdateIndexRequest(proto.Message): + r"""Request message for UpdateIndex. + + Attributes: + index (google.cloud.visionai_v1.types.Index): + Required. The resource being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Index resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field of the resource will be + overwritten if it is in the mask. Empty field mask is not + allowed. If the mask is "*", it triggers a full update of + the index, and also a whole rebuild of index data. + """ + + index: 'Index' = proto.Field( + proto.MESSAGE, + number=1, + message='Index', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateIndexMetadata(proto.Message): + r"""Metadata message for UpdateIndexRequest + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class GetIndexRequest(proto.Message): + r"""Request message for getting an Index. + + Attributes: + name (str): + Required. Name of the Index resource. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListIndexesRequest(proto.Message): + r"""Request message for listing Indexes. + + Attributes: + parent (str): + Required. The parent corpus that owns this collection of + indexes. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + page_size (int): + The maximum number of indexes to return. The + service may return fewer than this value. + If unspecified, at most 50 indexes will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListIndexes`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListIndexes`` must match the call that provided the page + token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListIndexesResponse(proto.Message): + r"""Response message for ListIndexes. + + Attributes: + indexes (MutableSequence[google.cloud.visionai_v1.types.Index]): + The indexes under the specified corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + indexes: MutableSequence['Index'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Index', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteIndexRequest(proto.Message): + r"""Request message for DeleteIndex. + + Attributes: + name (str): + Required. The name of the index to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteIndexMetadata(proto.Message): + r"""Metadata message for DeleteIndexRequest + """ + + +class Index(proto.Message): + r"""An Index is a resource in Corpus. It contains an indexed + version of the assets and annotations. When deployed to an + endpoint, it will allow users to search the Index. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + entire_corpus (bool): + Include all assets under the corpus. + + This field is a member of `oneof`_ ``asset_filter``. + name (str): + Output only. Resource name of the Index resource. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/indexes/{index_id}`` + display_name (str): + Optional. Optional user-specified display + name of the index. + description (str): + Optional. Optional description of the index. + state (google.cloud.visionai_v1.types.Index.State): + Output only. State of the index. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + deployed_indexes (MutableSequence[google.cloud.visionai_v1.types.DeployedIndexReference]): + Output only. References to the deployed index instance. + Index of VIDEO_ON_DEMAND corpus can have at most one + deployed index. Index of IMAGE corpus can have multiple + deployed indexes. + """ + class State(proto.Enum): + r"""Enum representing the different states through which an Index + might cycle during its lifetime. + + Values: + STATE_UNSPECIFIED (0): + The default value. Should not be used. + CREATING (1): + State CREATING. + CREATED (2): + State CREATED. + UPDATING (3): + State UPDATING. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + CREATED = 2 + UPDATING = 3 + + entire_corpus: bool = proto.Field( + proto.BOOL, + number=9, + oneof='asset_filter', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + deployed_indexes: MutableSequence['DeployedIndexReference'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='DeployedIndexReference', + ) + + +class DeployedIndexReference(proto.Message): + r"""Points to a DeployedIndex. + + Attributes: + index_endpoint (str): + Immutable. A resource name of the + IndexEndpoint. + """ + + index_endpoint: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Corpus(proto.Message): + r"""Corpus is a set of media contents for management. + Within a corpus, media shares the same data schema. Search is + also restricted within a single corpus. + + Attributes: + name (str): + Resource name of the corpus. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + display_name (str): + Required. The corpus name to shown in the UI. + The name can be up to 32 characters long. + description (str): + Optional. Description of the corpus. Can be + up to 25000 characters long. + default_ttl (google.protobuf.duration_pb2.Duration): + Optional. The default TTL value for all assets under the + corpus without a asset level user-defined TTL. For + STREAM_VIDEO type corpora, this is required and the maximum + allowed default_ttl is 10 years. + type_ (google.cloud.visionai_v1.types.Corpus.Type): + Optional. Type of the asset inside corpus. + search_capability_setting (google.cloud.visionai_v1.types.SearchCapabilitySetting): + Default search capability setting on corpus + level. + """ + class Type(proto.Enum): + r"""Type of the asset inside the corpus. + + Values: + TYPE_UNSPECIFIED (0): + The default type, not supposed to be used. If this default + type is used, the corpus will be created as STREAM_VIDEO + corpus. + STREAM_VIDEO (1): + Asset is a live streaming video. + IMAGE (2): + Asset is an image. + VIDEO_ON_DEMAND (3): + Asset is a batch video. + """ + TYPE_UNSPECIFIED = 0 + STREAM_VIDEO = 1 + IMAGE = 2 + VIDEO_ON_DEMAND = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + default_ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + type_: Type = proto.Field( + proto.ENUM, + number=7, + enum=Type, + ) + search_capability_setting: 'SearchCapabilitySetting' = proto.Field( + proto.MESSAGE, + number=8, + message='SearchCapabilitySetting', + ) + + +class GetCorpusRequest(proto.Message): + r"""Request message for GetCorpus. + + Attributes: + name (str): + Required. The resource name of the corpus to + retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCorpusRequest(proto.Message): + r"""Request message for UpdateCorpus. + + Attributes: + corpus (google.cloud.visionai_v1.types.Corpus): + Required. The corpus which replaces the + resource on the server. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + corpus: 'Corpus' = proto.Field( + proto.MESSAGE, + number=1, + message='Corpus', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListCorporaRequest(proto.Message): + r"""Request message for ListCorpora. + + Attributes: + parent (str): + Required. The resource name of the project + from which to list corpora. + page_size (int): + Requested page size. API may return fewer results than + requested. If negative, INVALID_ARGUMENT error will be + returned. If unspecified or 0, API will pick a default size, + which is 10. If the requested page size is larger than the + maximum size, API will pick use the maximum size, which is + 20. + page_token (str): + A token identifying a page of results for the server to + return. Typically obtained via + [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] + of the previous + [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] + call. + filter (str): + The filter applied to the returned corpora list. Only the + following restrictions are supported: + ``type=``, ``type!=``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListCorporaResponse(proto.Message): + r"""Response message for ListCorpora. + + Attributes: + corpora (MutableSequence[google.cloud.visionai_v1.types.Corpus]): + The corpora in the project. + next_page_token (str): + A token to retrieve next page of results. Pass to + [ListCorporaRequest.page_token][google.cloud.visionai.v1.ListCorporaRequest.page_token] + to obtain that page. + """ + + @property + def raw_page(self): + return self + + corpora: MutableSequence['Corpus'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Corpus', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteCorpusRequest(proto.Message): + r"""Request message for DeleteCorpus. + + Attributes: + name (str): + Required. The resource name of the corpus to + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AnalyzeCorpusRequest(proto.Message): + r"""Request message for AnalyzeCorpus. + + Attributes: + name (str): + Required. The parent corpus resource where the assets will + be analyzed. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AnalyzeCorpusMetadata(proto.Message): + r"""The metadata message for AnalyzeCorpus LRO. + + Attributes: + metadata (google.cloud.visionai_v1.types.OperationMetadata): + The metadata of the operation. + """ + + metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class AnalyzeCorpusResponse(proto.Message): + r"""The response message for AnalyzeCorpus LRO. + """ + + +class CreateDataSchemaRequest(proto.Message): + r"""Request message for CreateDataSchema. + + Attributes: + parent (str): + Required. The parent resource where this data schema will be + created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + data_schema (google.cloud.visionai_v1.types.DataSchema): + Required. The data schema to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_schema: 'DataSchema' = proto.Field( + proto.MESSAGE, + number=2, + message='DataSchema', + ) + + +class DataSchema(proto.Message): + r"""Data schema indicates how the user specified annotation is + interpreted in the system. + + Attributes: + name (str): + Resource name of the data schema in the form of: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`` + where {data_schema} part should be the same as the ``key`` + field below. + key (str): + Required. The key of this data schema. This key should be + matching the key of user specified annotation and unique + inside corpus. This value can be up to 63 characters, and + valid characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + schema_details (google.cloud.visionai_v1.types.DataSchemaDetails): + The schema details mapping to the key. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + key: str = proto.Field( + proto.STRING, + number=2, + ) + schema_details: 'DataSchemaDetails' = proto.Field( + proto.MESSAGE, + number=3, + message='DataSchemaDetails', + ) + + +class DataSchemaDetails(proto.Message): + r"""Data schema details indicates the data type and the data + struct corresponding to the key of user specified annotation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.cloud.visionai_v1.types.DataSchemaDetails.DataType): + Type of the annotation. + + This field is a member of `oneof`_ ``_type``. + proto_any_config (google.cloud.visionai_v1.types.DataSchemaDetails.ProtoAnyConfig): + Config for protobuf any type. + list_config (google.cloud.visionai_v1.types.DataSchemaDetails.ListConfig): + Config for List data type. + customized_struct_config (google.cloud.visionai_v1.types.DataSchemaDetails.CustomizedStructConfig): + Config for CustomizedStruct data type. + granularity (google.cloud.visionai_v1.types.DataSchemaDetails.Granularity): + The granularity associated with this + DataSchema. + + This field is a member of `oneof`_ ``_granularity``. + search_strategy (google.cloud.visionai_v1.types.DataSchemaDetails.SearchStrategy): + The search strategy to be applied on the ``key`` above. + """ + class DataType(proto.Enum): + r"""Data type of the annotation. + + Values: + DATA_TYPE_UNSPECIFIED (0): + Unspecified type. + INTEGER (1): + Integer type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + IntRangeArray. + FLOAT (2): + Float type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + FloatRangeArray. + STRING (3): + String type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH, + - DataSchema.SearchStrategy.SMART_SEARCH. + DATETIME (5): + Supported formats: %Y-%m-%dT%H:%M:%E\ *S%E*\ z + (absl::RFC3339_full) %Y-%m-%dT%H:%M:%E\ *S + %Y-%m-%dT%H:%M%E*\ z %Y-%m-%dT%H:%M %Y-%m-%dT%H%E\ *z + %Y-%m-%dT%H %Y-%m-%d%E*\ z %Y-%m-%d %Y-%m %Y Allowed search + strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + DateTimeRangeArray. + GEO_COORDINATE (7): + Geo coordinate type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + GeoLocationArray. + PROTO_ANY (8): + Type to pass any proto as available in annotations.proto. + Only use internally. Available proto types and its + corresponding search behavior: + + - ImageObjectDetectionPredictionResult, allows SMART_SEARCH + on display_names and NO_SEARCH. + - ClassificationPredictionResult, allows SMART_SEARCH on + display_names and NO_SEARCH. + - ImageSegmentationPredictionResult, allows NO_SEARCH. + - VideoActionRecognitionPredictionResult, allows + SMART_SEARCH on display_name and NO_SEARCH. + - VideoObjectTrackingPredictionResult, allows SMART_SEARCH + on display_name and NO_SEARCH. + - VideoClassificationPredictionResult, allows SMART_SEARCH + on display_name and NO_SEARCH. + - OccupancyCountingPredictionResult, allows EXACT_SEARCH on + stats.full_frame_count.count and NO_SEARCH. + - ObjectDetectionPredictionResult, allows SMART_SEARCH on + identified_boxes.entity.label_string and NO_SEARCH. + BOOLEAN (9): + Boolean type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. + LIST (10): + List type. + + - Each element in the list must be of the exact same data + schema; otherwise, they are invalid arguments. + - List level cannot set search strategy. Leaf node level + can do. + - Elements cannot be another list (no list of list). + - Elements can be CUSTOMIZED_STRUCT, and max number of + layers is 10. + CUSTOMIZED_STRUCT (6): + Struct type. + + - SearchStrategy: + + - Data Schema that's CUSTOMIZED_STRUCT cannot set search + strategy. + - Leaf-node elements allow setting search strategy based + on element's SearchStrategy restriction. + + - Nested layer restrictions: + + - Data Schema that's CUSTOMIZED_STRUCT allows its fields + to be of CUSTOMIZED_STRUCT as well, but the overall + layers restriction is 10. + """ + DATA_TYPE_UNSPECIFIED = 0 + INTEGER = 1 + FLOAT = 2 + STRING = 3 + DATETIME = 5 + GEO_COORDINATE = 7 + PROTO_ANY = 8 + BOOLEAN = 9 + LIST = 10 + CUSTOMIZED_STRUCT = 6 + + class Granularity(proto.Enum): + r"""The granularity of annotations under this DataSchema. + + Values: + GRANULARITY_UNSPECIFIED (0): + Unspecified granularity. + GRANULARITY_ASSET_LEVEL (1): + Asset-level granularity (annotations must not + contain partition info). + GRANULARITY_PARTITION_LEVEL (2): + Partition-level granularity (annotations must + contain partition info). + """ + GRANULARITY_UNSPECIFIED = 0 + GRANULARITY_ASSET_LEVEL = 1 + GRANULARITY_PARTITION_LEVEL = 2 + + class ProtoAnyConfig(proto.Message): + r"""The configuration for ``PROTO_ANY`` data type. + + Attributes: + type_uri (str): + The type URI of the proto message. + """ + + type_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class ListConfig(proto.Message): + r"""The configuration for ``LIST`` data type. + + Attributes: + value_schema (google.cloud.visionai_v1.types.DataSchemaDetails): + The value's data schema in the list. + """ + + value_schema: 'DataSchemaDetails' = proto.Field( + proto.MESSAGE, + number=1, + message='DataSchemaDetails', + ) + + class CustomizedStructConfig(proto.Message): + r"""The configuration for ``CUSTOMIZED_STRUCT`` data type. + + Attributes: + field_schemas (MutableMapping[str, google.cloud.visionai_v1.types.DataSchemaDetails]): + Direct child elements data schemas. + """ + + field_schemas: MutableMapping[str, 'DataSchemaDetails'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='DataSchemaDetails', + ) + + class SearchStrategy(proto.Message): + r"""The search strategy for annotations value of the ``key``. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_strategy_type (google.cloud.visionai_v1.types.DataSchemaDetails.SearchStrategy.SearchStrategyType): + The type of search strategy to be applied on the ``key`` + above. The allowed ``search_strategy_type`` is different for + different data types, which is documented in the + DataSchemaDetails.DataType. Specifying unsupported + ``search_strategy_type`` for data types will result in + INVALID_ARGUMENT error. + + This field is a member of `oneof`_ ``_search_strategy_type``. + confidence_score_index_config (google.cloud.visionai_v1.types.DataSchemaDetails.SearchStrategy.ConfidenceScoreIndexConfig): + Optional. Configs the path to the confidence score, and the + threshold. Only if the score is greater than the threshold, + current field will be built into the index. Only applies to + leaf nodes using EXACT_SEARCH or SMART_SEARCH. + """ + class SearchStrategyType(proto.Enum): + r"""The types of search strategies to be applied on the + annotation key. + + Values: + NO_SEARCH (0): + Annotatation values of the ``key`` above will not be + searchable. + EXACT_SEARCH (1): + When searching with ``key``, the value must be exactly as + the annotation value that has been ingested. + SMART_SEARCH (2): + When searching with ``key``, Warehouse will perform broad + search based on semantic of the annotation value. + """ + NO_SEARCH = 0 + EXACT_SEARCH = 1 + SMART_SEARCH = 2 + + class ConfidenceScoreIndexConfig(proto.Message): + r"""Filter on the confidence score. Only adds to index if the confidence + score is higher than the threshold. Example data schema: key: + "name-confidence-pair" type: CUSTOMIZED_STRUCT granularity: + GRANULARITY_PARTITION_LEVEL customized_struct_config { field_schemas + { key: "name" type: STRING granularity: GRANULARITY_PARTITION_LEVEL + search_strategy { search_strategy_type: SMART_SEARCH + confidence_score_index_config { field_path: + "name-confidence-pair.score" threshold: 0.6 } } } field_schemas { + key: "score" type: FLOAT granularity: GRANULARITY_PARTITION_LEVEL } + } This means only "name" with score > 0.6 will be indexed. + + Attributes: + field_path (str): + Required. The path to the confidence score field. It is a + string that concatenates all the data schema keys along the + path. See the example above. If the data schema contains + LIST, use '_ENTRIES' to concatenate. Example data schema + contains a list: "key": "list-name-score", "schemaDetails": + { "type": "LIST", "granularity": + "GRANULARITY_PARTITION_LEVEL", "listConfig": { + "valueSchema": { "type": "CUSTOMIZED_STRUCT", "granularity": + "GRANULARITY_PARTITION_LEVEL", "customizedStructConfig": { + "fieldSchemas": { "name": { "type": "STRING", "granularity": + "GRANULARITY_PARTITION_LEVEL", "searchStrategy": { + "searchStrategyType": "SMART_SEARCH" + "confidence_score_index_config": { "field_path": + "list-name-score._ENTRIES.score", "threshold": "0.9", } } }, + "score": { "type": "FLOAT", "granularity": + "GRANULARITY_PARTITION_LEVEL", } } } } } } + threshold (float): + Required. The threshold. + """ + + field_path: str = proto.Field( + proto.STRING, + number=1, + ) + threshold: float = proto.Field( + proto.FLOAT, + number=2, + ) + + search_strategy_type: 'DataSchemaDetails.SearchStrategy.SearchStrategyType' = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum='DataSchemaDetails.SearchStrategy.SearchStrategyType', + ) + confidence_score_index_config: 'DataSchemaDetails.SearchStrategy.ConfidenceScoreIndexConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='DataSchemaDetails.SearchStrategy.ConfidenceScoreIndexConfig', + ) + + type_: DataType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=DataType, + ) + proto_any_config: ProtoAnyConfig = proto.Field( + proto.MESSAGE, + number=6, + message=ProtoAnyConfig, + ) + list_config: ListConfig = proto.Field( + proto.MESSAGE, + number=8, + message=ListConfig, + ) + customized_struct_config: CustomizedStructConfig = proto.Field( + proto.MESSAGE, + number=9, + message=CustomizedStructConfig, + ) + granularity: Granularity = proto.Field( + proto.ENUM, + number=5, + optional=True, + enum=Granularity, + ) + search_strategy: SearchStrategy = proto.Field( + proto.MESSAGE, + number=7, + message=SearchStrategy, + ) + + +class UpdateDataSchemaRequest(proto.Message): + r"""Request message for UpdateDataSchema. + + Attributes: + data_schema (google.cloud.visionai_v1.types.DataSchema): + Required. The data schema's ``name`` field is used to + identify the data schema to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + data_schema: 'DataSchema' = proto.Field( + proto.MESSAGE, + number=1, + message='DataSchema', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetDataSchemaRequest(proto.Message): + r"""Request message for GetDataSchema. + + Attributes: + name (str): + Required. The name of the data schema to retrieve. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteDataSchemaRequest(proto.Message): + r"""Request message for DeleteDataSchema. + + Attributes: + name (str): + Required. The name of the data schema to delete. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDataSchemasRequest(proto.Message): + r"""Request message for ListDataSchemas. + + Attributes: + parent (str): + Required. The parent, which owns this collection of data + schemas. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + page_size (int): + The maximum number of data schemas to return. + The service may return fewer than this value. If + unspecified, at most 50 data schemas will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListDataSchemas`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDataSchemas`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDataSchemasResponse(proto.Message): + r"""Response message for ListDataSchemas. + + Attributes: + data_schemas (MutableSequence[google.cloud.visionai_v1.types.DataSchema]): + The data schemas from the specified corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + data_schemas: MutableSequence['DataSchema'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DataSchema', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAnnotationRequest(proto.Message): + r"""Request message for CreateAnnotation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource where this annotation will be + created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + annotation (google.cloud.visionai_v1.types.Annotation): + Required. The annotation to create. + annotation_id (str): + Optional. The ID to use for the annotation, which will + become the final component of the annotation's resource name + if user choose to specify. Otherwise, annotation id will be + generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must be a + letter, the last could be a letter or a number. + + This field is a member of `oneof`_ ``_annotation_id``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + annotation: 'Annotation' = proto.Field( + proto.MESSAGE, + number=2, + message='Annotation', + ) + annotation_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class Annotation(proto.Message): + r"""An annotation is a resource in asset. It represents a + key-value mapping of content in asset. + + Attributes: + name (str): + Resource name of the annotation. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + user_specified_annotation (google.cloud.visionai_v1.types.UserSpecifiedAnnotation): + User provided annotation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + user_specified_annotation: 'UserSpecifiedAnnotation' = proto.Field( + proto.MESSAGE, + number=2, + message='UserSpecifiedAnnotation', + ) + + +class UserSpecifiedAnnotation(proto.Message): + r"""Annotation provided by users. + + Attributes: + key (str): + Required. Key of the annotation. The key must + be set with type by CreateDataSchema. + value (google.cloud.visionai_v1.types.AnnotationValue): + Value of the annotation. The value must be + able to convert to the type according to the + data schema. + partition (google.cloud.visionai_v1.types.Partition): + Partition information in time and space for + the sub-asset level annotation. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: 'AnnotationValue' = proto.Field( + proto.MESSAGE, + number=2, + message='AnnotationValue', + ) + partition: 'Partition' = proto.Field( + proto.MESSAGE, + number=3, + message='Partition', + ) + + +class GeoCoordinate(proto.Message): + r"""Location Coordinate Representation + + Attributes: + latitude (float): + Latitude Coordinate. Degrees [-90 .. 90] + longitude (float): + Longitude Coordinate. Degrees [-180 .. 180] + """ + + latitude: float = proto.Field( + proto.DOUBLE, + number=1, + ) + longitude: float = proto.Field( + proto.DOUBLE, + number=2, + ) + + +class AnnotationValue(proto.Message): + r"""Value of annotation, including all types available in data + schema. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + int_value (int): + Value of int type annotation. + + This field is a member of `oneof`_ ``value``. + float_value (float): + Value of float type annotation. + + This field is a member of `oneof`_ ``value``. + str_value (str): + Value of string type annotation. + + This field is a member of `oneof`_ ``value``. + datetime_value (str): + Value of date time type annotation. + + This field is a member of `oneof`_ ``value``. + geo_coordinate (google.cloud.visionai_v1.types.GeoCoordinate): + Value of geo coordinate type annotation. + + This field is a member of `oneof`_ ``value``. + proto_any_value (google.protobuf.any_pb2.Any): + Value of any proto value. + + This field is a member of `oneof`_ ``value``. + bool_value (bool): + Value of boolean type annotation. + + This field is a member of `oneof`_ ``value``. + customized_struct_data_value (google.protobuf.struct_pb2.Struct): + Value of customized struct annotation. This field does not + have effects. Use customized_struct_value instead for + customized struct annotation. + + This field is a member of `oneof`_ ``value``. + list_value (google.cloud.visionai_v1.types.AnnotationList): + Value of list type annotation. + + This field is a member of `oneof`_ ``value``. + customized_struct_value (google.cloud.visionai_v1.types.AnnotationCustomizedStruct): + Value of custom struct type annotation. + + This field is a member of `oneof`_ ``value``. + """ + + int_value: int = proto.Field( + proto.INT64, + number=1, + oneof='value', + ) + float_value: float = proto.Field( + proto.FLOAT, + number=2, + oneof='value', + ) + str_value: str = proto.Field( + proto.STRING, + number=3, + oneof='value', + ) + datetime_value: str = proto.Field( + proto.STRING, + number=5, + oneof='value', + ) + geo_coordinate: 'GeoCoordinate' = proto.Field( + proto.MESSAGE, + number=7, + oneof='value', + message='GeoCoordinate', + ) + proto_any_value: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=8, + oneof='value', + message=any_pb2.Any, + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=9, + oneof='value', + ) + customized_struct_data_value: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=10, + oneof='value', + message=struct_pb2.Struct, + ) + list_value: 'AnnotationList' = proto.Field( + proto.MESSAGE, + number=11, + oneof='value', + message='AnnotationList', + ) + customized_struct_value: 'AnnotationCustomizedStruct' = proto.Field( + proto.MESSAGE, + number=6, + oneof='value', + message='AnnotationCustomizedStruct', + ) + + +class AnnotationList(proto.Message): + r"""List representation in annotation. + + Attributes: + values (MutableSequence[google.cloud.visionai_v1.types.AnnotationValue]): + The values of ``LIST`` data type annotation. + """ + + values: MutableSequence['AnnotationValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnnotationValue', + ) + + +class AnnotationCustomizedStruct(proto.Message): + r"""Customized struct represnation in annotation. + + Attributes: + elements (MutableMapping[str, google.cloud.visionai_v1.types.AnnotationValue]): + A map from elements' keys to element's + annotation value. + """ + + elements: MutableMapping[str, 'AnnotationValue'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='AnnotationValue', + ) + + +class ListAnnotationsRequest(proto.Message): + r"""Request message for GetAnnotation API. + + Attributes: + parent (str): + The parent, which owns this collection of annotations. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}`` + page_size (int): + The maximum number of annotations to return. + The service may return fewer than this value. If + unspecified, at most 50 annotations will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListAnnotations`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListAnnotations`` must match the call that provided the + page token. + filter (str): + The filter applied to the returned list. We only support + filtering for the following fields: For corpus of + STREAM_VIDEO type: + ``partition.temporal_partition.start_time``, + ``partition.temporal_partition.end_time``, and ``key``. For + corpus of VIDEO_ON_DEMAND type, + ``partition.relative_temporal_partition.start_offset``, + ``partition.relative_temporal_partition.end_offset``, and + ``key``. For corpus of IMAGE type, only ``key`` is + supported. Timestamps are specified in the RFC-3339 format, + and only one restriction may be applied per field, joined by + conjunctions. Format: + "partition.temporal_partition.start_time > + "2012-04-21T11:30:00-04:00" AND + partition.temporal_partition.end_time < + "2012-04-22T11:30:00-04:00" AND key = "example_key"". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnnotationsResponse(proto.Message): + r"""Request message for ListAnnotations API. + + Attributes: + annotations (MutableSequence[google.cloud.visionai_v1.types.Annotation]): + The annotations from the specified asset. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + annotations: MutableSequence['Annotation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Annotation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAnnotationRequest(proto.Message): + r"""Request message for GetAnnotation API. + + Attributes: + name (str): + Required. The name of the annotation to retrieve. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAnnotationRequest(proto.Message): + r"""Request message for UpdateAnnotation API. + + Attributes: + annotation (google.cloud.visionai_v1.types.Annotation): + Required. The annotation to update. The annotation's + ``name`` field is used to identify the annotation to be + updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + annotation: 'Annotation' = proto.Field( + proto.MESSAGE, + number=1, + message='Annotation', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAnnotationRequest(proto.Message): + r"""Request message for DeleteAnnotation API. + + Attributes: + name (str): + Required. The name of the annotation to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ImportAssetsRequest(proto.Message): + r"""The request message for ImportAssets. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + assets_gcs_uri (str): + The file contains all assets information to be imported. + + - The file is in JSONL format. + - Each line corresponding to one asset. + - Each line will be converted into InputImageAsset proto. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent corpus resource where the assets will + be imported. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + """ + + assets_gcs_uri: str = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ImportAssetsMetadata(proto.Message): + r"""The metadata message for ImportAssets LRO. + + Attributes: + metadata (google.cloud.visionai_v1.types.OperationMetadata): + The metadata of the operation. + """ + + metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class ImportAssetsResponse(proto.Message): + r"""The response message for ImportAssets LRO. + """ + + +class CreateSearchConfigRequest(proto.Message): + r"""Request message for CreateSearchConfig. + + Attributes: + parent (str): + Required. The parent resource where this search + configuration will be created. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + search_config (google.cloud.visionai_v1.types.SearchConfig): + Required. The search config to create. + search_config_id (str): + Required. ID to use for the new search config. Will become + the final component of the SearchConfig's resource name. + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-_/. The first character must be a + letter, the last could be a letter or a number. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + search_config: 'SearchConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='SearchConfig', + ) + search_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSearchConfigRequest(proto.Message): + r"""Request message for UpdateSearchConfig. + + Attributes: + search_config (google.cloud.visionai_v1.types.SearchConfig): + Required. The search configuration to update. + + The search configuration's ``name`` field is used to + identify the resource to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If left + unset, all field paths will be + updated/overwritten. + """ + + search_config: 'SearchConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchConfig', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetSearchConfigRequest(proto.Message): + r"""Request message for GetSearchConfig. + + Attributes: + name (str): + Required. The name of the search configuration to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteSearchConfigRequest(proto.Message): + r"""Request message for DeleteSearchConfig. + + Attributes: + name (str): + Required. The name of the search configuration to delete. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSearchConfigsRequest(proto.Message): + r"""Request message for ListSearchConfigs. + + Attributes: + parent (str): + Required. The parent, which owns this collection of search + configurations. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + page_size (int): + The maximum number of search configurations + to return. The service may return fewer than + this value. If unspecified, a page size of 50 + will be used. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListSearchConfigs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListSearchConfigs`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSearchConfigsResponse(proto.Message): + r"""Response message for ListSearchConfigs. + + Attributes: + search_configs (MutableSequence[google.cloud.visionai_v1.types.SearchConfig]): + The search configurations from the specified + corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + search_configs: MutableSequence['SearchConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchConfig(proto.Message): + r"""SearchConfig stores different properties that will affect + search behaviors and search results. + + Attributes: + name (str): + Resource name of the search configuration. For + CustomSearchCriteria, search_config would be the search + operator name. For Facets, search_config would be the facet + dimension name. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + facet_property (google.cloud.visionai_v1.types.FacetProperty): + Establishes a FacetDimension and associated + specifications. + search_criteria_property (google.cloud.visionai_v1.types.SearchCriteriaProperty): + Creates a mapping between a custom + SearchCriteria and one or more UGA keys. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + facet_property: 'FacetProperty' = proto.Field( + proto.MESSAGE, + number=2, + message='FacetProperty', + ) + search_criteria_property: 'SearchCriteriaProperty' = proto.Field( + proto.MESSAGE, + number=3, + message='SearchCriteriaProperty', + ) + + +class IndexEndpoint(proto.Message): + r"""Message representing IndexEndpoint resource. Indexes are + deployed into it. + + Attributes: + name (str): + Output only. Resource name of the IndexEndpoint. Format: + ``projects/{project}/locations/{location}/indexEndpoints/{index_endpoint_id}`` + display_name (str): + Optional. Display name of the IndexEndpoint. + Can be up to 32 characters long. + description (str): + Optional. Description of the IndexEndpoint. + Can be up to 25000 characters long. + deployed_index (google.cloud.visionai_v1.types.DeployedIndex): + Output only. The Index deployed in this + IndexEndpoint. + state (google.cloud.visionai_v1.types.IndexEndpoint.State): + Output only. IndexEndpoint state. + labels (MutableMapping[str, str]): + Optional. The labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update timestamp. + """ + class State(proto.Enum): + r"""IndexEndpoint stage. + + Values: + STATE_UNSPECIFIED (0): + The default value. Should not be used. + CREATING (1): + State CREATING. + CREATED (2): + State CREATED. + UPDATING (3): + State UPDATING. + FAILED (4): + State FAILED. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + CREATED = 2 + UPDATING = 3 + FAILED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + deployed_index: 'DeployedIndex' = proto.Field( + proto.MESSAGE, + number=9, + message='DeployedIndex', + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class CreateIndexEndpointRequest(proto.Message): + r"""Request message for CreateIndexEndpoint. + + Attributes: + parent (str): + Required. Format: + ``projects/{project}/locations/{location}`` + index_endpoint_id (str): + Optional. The ID to use for the + IndexEndpoint, which will become the final + component of the IndexEndpoint's resource name + if the user specifies it. Otherwise, + IndexEndpoint id will be autogenerated. + + This value should be up to 63 characters, and + valid characters are a-z, 0-9 and dash (-). The + first character must be a letter, the last must + be a letter or a number. + index_endpoint (google.cloud.visionai_v1.types.IndexEndpoint): + Required. The resource being created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + index_endpoint_id: str = proto.Field( + proto.STRING, + number=2, + ) + index_endpoint: 'IndexEndpoint' = proto.Field( + proto.MESSAGE, + number=3, + message='IndexEndpoint', + ) + + +class CreateIndexEndpointMetadata(proto.Message): + r"""Metadata message for CreateIndexEndpoint. + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class GetIndexEndpointRequest(proto.Message): + r"""Request message for GetIndexEndpoint. + + Attributes: + name (str): + Required. Name of the IndexEndpoint resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListIndexEndpointsRequest(proto.Message): + r"""Request message for ListIndexEndpoints. + + Attributes: + parent (str): + Required. Format: + ``projects/{project}/locations/{location}`` + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. The service + may return fewer than this value. If + unspecified, a page size of 50 will be used. The + maximum value is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. The filter applied to the returned list. We only + support filtering for the + ``deployed_image_index.image_index`` field. However, to + filter by a corpus instead of an image index, simply use + ``deployed_image_index.corpus``, which will return all + endpoints with ``deployed_image_index.image_index`` inside + of the given corpus. A basic filter on image index would + look like: deployed_image_index.image_index = + "projects/123/locations/us-central1/corpora/my_corpus/imageIndexes/my_image_index" + A basic filter on corpus would look like: + deployed_image_index.corpus = + "projects/123/locations/us-central1/corpora/my_corpus". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListIndexEndpointsResponse(proto.Message): + r"""Response message for ListIndexEndpoints. + + Attributes: + index_endpoints (MutableSequence[google.cloud.visionai_v1.types.IndexEndpoint]): + The list of IndexEndpoints. + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + index_endpoints: MutableSequence['IndexEndpoint'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IndexEndpoint', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateIndexEndpointRequest(proto.Message): + r"""Request message for UpdateIndexEndpoint. + + Attributes: + index_endpoint (google.cloud.visionai_v1.types.IndexEndpoint): + Required. The resource being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the IndexEndpoint resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field of the resource will + be overwritten if it is in the mask. Empty field mask is not + allowed. If the mask is "*", then this is a full replacement + of the resource. + """ + + index_endpoint: 'IndexEndpoint' = proto.Field( + proto.MESSAGE, + number=1, + message='IndexEndpoint', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateIndexEndpointMetadata(proto.Message): + r"""Metadata message for UpdateIndexEndpoint. + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class DeleteIndexEndpointRequest(proto.Message): + r"""Request message for DeleteIndexEndpoint. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteIndexEndpointMetadata(proto.Message): + r"""Metadata message for DeleteIndexEndpoint. + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + + +class DeployIndexRequest(proto.Message): + r"""Request message for DeployIndex. + + Attributes: + index_endpoint (str): + Required. IndexEndpoint the index is deployed to. Format: + ``projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}`` + deployed_index (google.cloud.visionai_v1.types.DeployedIndex): + Required. Index to deploy. + """ + + index_endpoint: str = proto.Field( + proto.STRING, + number=1, + ) + deployed_index: 'DeployedIndex' = proto.Field( + proto.MESSAGE, + number=3, + message='DeployedIndex', + ) + + +class DeployIndexResponse(proto.Message): + r"""DeployIndex response once the operation is done. + """ + + +class DeployIndexMetadata(proto.Message): + r"""Metadata message for DeployIndex. + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + deployed_index (str): + Output only. The index being deployed. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + deployed_index: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UndeployIndexMetadata(proto.Message): + r"""Metadata message for UndeployIndex. + + Attributes: + operation_metadata (google.cloud.visionai_v1.types.OperationMetadata): + Common metadata of the long-running + operation. + deployed_index (str): + Output only. The index being undeployed. + """ + + operation_metadata: common.OperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=common.OperationMetadata, + ) + deployed_index: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UndeployIndexRequest(proto.Message): + r"""Request message for UndeployIndexEndpoint. + + Attributes: + index_endpoint (str): + Required. Resource name of the IndexEndpoint resource on + which the undeployment will act. Format: + ``projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}`` + """ + + index_endpoint: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeployIndexResponse(proto.Message): + r"""UndeployIndex response once the operation is done. + """ + + +class DeployedIndex(proto.Message): + r"""A deployment of an Index. + + Attributes: + index (str): + Required. Name of the deployed Index. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/indexes/{index_id}`` + """ + + index: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FacetProperty(proto.Message): + r"""Central configuration for a facet. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + fixed_range_bucket_spec (google.cloud.visionai_v1.types.FacetProperty.FixedRangeBucketSpec): + Fixed range facet bucket config. + + This field is a member of `oneof`_ ``range_facet_config``. + custom_range_bucket_spec (google.cloud.visionai_v1.types.FacetProperty.CustomRangeBucketSpec): + Custom range facet bucket config. + + This field is a member of `oneof`_ ``range_facet_config``. + datetime_bucket_spec (google.cloud.visionai_v1.types.FacetProperty.DateTimeBucketSpec): + Datetime range facet bucket config. + + This field is a member of `oneof`_ ``range_facet_config``. + mapped_fields (MutableSequence[str]): + Name of the facets, which are the dimensions users want to + use to refine search results. ``mapped_fields`` will match + UserSpecifiedDataSchema keys. + + For example, user can add a bunch of UGAs with the same key, + such as player:adam, player:bob, player:charles. When + multiple mapped_fields are specified, will merge their value + together as final facet value. E.g. home_team: a, + home_team:b, away_team:a, away_team:c, when facet_field = + [home_team, away_team], facet_value will be [a, b, c]. + + UNLESS this is a 1:1 facet dimension (mapped_fields.size() + == 1) AND the mapped_field equals the parent + SearchConfig.name, the parent must also contain a + SearchCriteriaProperty that maps to the same fields. + mapped_fields must not be empty. + display_name (str): + Display name of the facet. To be used by UI + for facet rendering. + result_size (int): + Maximum number of unique bucket to return for one facet. + Bucket number can be large for high-cardinality facet such + as "player". We only return top-n most related ones to user. + If it's <= 0, the server will decide the appropriate + result_size. + bucket_type (google.cloud.visionai_v1.types.FacetBucketType): + Facet bucket type e.g. value, range. + """ + + class FixedRangeBucketSpec(proto.Message): + r"""If bucket type is FIXED_RANGE, specify how values are bucketized. + Use FixedRangeBucketSpec when you want to create multiple buckets + with equal granularities. Using integer bucket value as an example, + when bucket_start = 0, bucket_granularity = 10, bucket_count = 5, + this facet will be aggregated via the following buckets: [-inf, 0), + [0, 10), [10, 20), [20, 30), [30, inf). Notably, bucket_count <= 1 + is an invalid spec. + + Attributes: + bucket_start (google.cloud.visionai_v1.types.FacetValue): + Lower bound of the bucket. NOTE: Only integer + type is currently supported for this field. + bucket_granularity (google.cloud.visionai_v1.types.FacetValue): + Bucket granularity. NOTE: Only integer type + is currently supported for this field. + bucket_count (int): + Total number of buckets. + """ + + bucket_start: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=1, + message='FacetValue', + ) + bucket_granularity: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=2, + message='FacetValue', + ) + bucket_count: int = proto.Field( + proto.INT32, + number=3, + ) + + class CustomRangeBucketSpec(proto.Message): + r"""If bucket type is CUSTOM_RANGE, specify how values are bucketized. + Use integer bucket value as an example, when the endpoints are 0, + 10, 100, and 1000, we will generate the following facets: [-inf, 0), + [0, 10), [10, 100), [100, 1000), [1000, inf). Notably: + + - endpoints must be listed in ascending order. Otherwise, the + SearchConfig API will reject the facet config. + - < 1 endpoints is an invalid spec. + + Attributes: + endpoints (MutableSequence[google.cloud.visionai_v1.types.FacetValue]): + Currently, only integer type is supported for + this field. + """ + + endpoints: MutableSequence['FacetValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FacetValue', + ) + + class DateTimeBucketSpec(proto.Message): + r"""If bucket type is DATE, specify how date values are + bucketized. + + Attributes: + granularity (google.cloud.visionai_v1.types.FacetProperty.DateTimeBucketSpec.Granularity): + Granularity of date type facet. + """ + class Granularity(proto.Enum): + r"""Granularity enum for the datetime bucket. + + Values: + GRANULARITY_UNSPECIFIED (0): + Unspecified granularity. + YEAR (1): + Granularity is year. + MONTH (2): + Granularity is month. + DAY (3): + Granularity is day. + """ + GRANULARITY_UNSPECIFIED = 0 + YEAR = 1 + MONTH = 2 + DAY = 3 + + granularity: 'FacetProperty.DateTimeBucketSpec.Granularity' = proto.Field( + proto.ENUM, + number=1, + enum='FacetProperty.DateTimeBucketSpec.Granularity', + ) + + fixed_range_bucket_spec: FixedRangeBucketSpec = proto.Field( + proto.MESSAGE, + number=5, + oneof='range_facet_config', + message=FixedRangeBucketSpec, + ) + custom_range_bucket_spec: CustomRangeBucketSpec = proto.Field( + proto.MESSAGE, + number=6, + oneof='range_facet_config', + message=CustomRangeBucketSpec, + ) + datetime_bucket_spec: DateTimeBucketSpec = proto.Field( + proto.MESSAGE, + number=7, + oneof='range_facet_config', + message=DateTimeBucketSpec, + ) + mapped_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + result_size: int = proto.Field( + proto.INT64, + number=3, + ) + bucket_type: 'FacetBucketType' = proto.Field( + proto.ENUM, + number=4, + enum='FacetBucketType', + ) + + +class SearchHypernym(proto.Message): + r"""Search resource: SearchHypernym. For example, { hypernym: "vehicle" + hyponyms: ["sedan", "truck"] } This means in SMART_SEARCH mode, + searching for "vehicle" will also return results with "sedan" or + "truck" as annotations. + + Attributes: + name (str): + Resource name of the SearchHypernym. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + hypernym (str): + Optional. The hypernym. + hyponyms (MutableSequence[str]): + Optional. Hyponyms that the hypernym is + mapped to. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + hypernym: str = proto.Field( + proto.STRING, + number=2, + ) + hyponyms: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateSearchHypernymRequest(proto.Message): + r"""Request message for creating SearchHypernym. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource where this SearchHypernym will + be created. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + search_hypernym (google.cloud.visionai_v1.types.SearchHypernym): + Required. The SearchHypernym to create. + search_hypernym_id (str): + Optional. The search hypernym id. + If omitted, a random UUID will be generated. + + This field is a member of `oneof`_ ``_search_hypernym_id``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + search_hypernym: 'SearchHypernym' = proto.Field( + proto.MESSAGE, + number=2, + message='SearchHypernym', + ) + search_hypernym_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class UpdateSearchHypernymRequest(proto.Message): + r"""Request message for updating SearchHypernym. + + Attributes: + search_hypernym (google.cloud.visionai_v1.types.SearchHypernym): + Required. The SearchHypernym to update. The search + hypernym's ``name`` field is used to identify the search + hypernym to be updated. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If left + unset, all field paths will be + updated/overwritten. + """ + + search_hypernym: 'SearchHypernym' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchHypernym', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetSearchHypernymRequest(proto.Message): + r"""Request message for getting SearchHypernym. + + Attributes: + name (str): + Required. The name of the SearchHypernym to retrieve. + Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteSearchHypernymRequest(proto.Message): + r"""Request message for deleting SearchHypernym. + + Attributes: + name (str): + Required. The name of the SearchHypernym to delete. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSearchHypernymsRequest(proto.Message): + r"""Request message for listing SearchHypernyms. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + SearchHypernyms. Format: + ``projects/{project_number}/locations/{location}/corpora/{corpus}`` + page_size (int): + The maximum number of SearchHypernyms + returned. The service may return fewer than this + value. If unspecified, a page size of 50 will be + used. The maximum value is 1000; values above + 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``SearchHypernym`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``SearchHypernym`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSearchHypernymsResponse(proto.Message): + r"""Response message for listing SearchHypernyms. + + Attributes: + search_hypernyms (MutableSequence[google.cloud.visionai_v1.types.SearchHypernym]): + The SearchHypernyms from the specified + corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + search_hypernyms: MutableSequence['SearchHypernym'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchHypernym', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchCriteriaProperty(proto.Message): + r"""Central configuration for custom search criteria. + + Attributes: + mapped_fields (MutableSequence[str]): + Each mapped_field corresponds to a UGA key. To understand + how this property works, take the following example. In the + SearchConfig table, the user adds this entry: search_config + { name: "person" search_criteria_property { mapped_fields: + "player" mapped_fields: "coach" } } + + Now, when a user issues a query like: criteria { field: + "person" text_array { txt_values: "Tom Brady" txt_values: + "Bill Belichick" } } + + MWH search will return search documents where (player=Tom + Brady \|\| coach=Tom Brady \|\| player=Bill Belichick \|\| + coach=Bill Belichick). + """ + + mapped_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class FacetValue(proto.Message): + r"""Definition of a single value with generic type. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_value (str): + String type value. + + This field is a member of `oneof`_ ``value``. + integer_value (int): + Integer type value. + + This field is a member of `oneof`_ ``value``. + datetime_value (google.type.datetime_pb2.DateTime): + Datetime type value. + + This field is a member of `oneof`_ ``value``. + """ + + string_value: str = proto.Field( + proto.STRING, + number=1, + oneof='value', + ) + integer_value: int = proto.Field( + proto.INT64, + number=2, + oneof='value', + ) + datetime_value: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=3, + oneof='value', + message=datetime_pb2.DateTime, + ) + + +class FacetBucket(proto.Message): + r"""Holds the facet value, selections state, and metadata. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (google.cloud.visionai_v1.types.FacetValue): + Singular value. + + This field is a member of `oneof`_ ``bucket_value``. + range_ (google.cloud.visionai_v1.types.FacetBucket.Range): + Range value. + + This field is a member of `oneof`_ ``bucket_value``. + selected (bool): + Whether one facet bucket is selected. This + field represents user's facet selection. It is + set by frontend in SearchVideosRequest. + """ + + class Range(proto.Message): + r"""The range of values [start, end) for which faceting is applied. + + Attributes: + start (google.cloud.visionai_v1.types.FacetValue): + Start of the range. Non-existence indicates + some bound (e.g. -inf). + end (google.cloud.visionai_v1.types.FacetValue): + End of the range. Non-existence indicates + some bound (e.g. inf). + """ + + start: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=1, + message='FacetValue', + ) + end: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=2, + message='FacetValue', + ) + + value: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=2, + oneof='bucket_value', + message='FacetValue', + ) + range_: Range = proto.Field( + proto.MESSAGE, + number=4, + oneof='bucket_value', + message=Range, + ) + selected: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class FacetGroup(proto.Message): + r"""A group of facet buckets to be passed back and forth between + backend & frontend. + + Attributes: + facet_id (str): + Unique id of the facet group. + display_name (str): + Display name of the facet. To be used by UI + for facet rendering. + buckets (MutableSequence[google.cloud.visionai_v1.types.FacetBucket]): + Buckets associated with the facet. E.g. for + "Team" facet, the bucket can be 49ers, patriots, + etc. + bucket_type (google.cloud.visionai_v1.types.FacetBucketType): + Facet bucket type. + fetch_matched_annotations (bool): + If true, return query matched annotations for this facet + group's selection. This option is only applicable for facets + based on partition level annotations. It supports the + following facet values: + + - INTEGER + - STRING (DataSchema.SearchStrategy.EXACT_SEARCH only) + """ + + facet_id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + buckets: MutableSequence['FacetBucket'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='FacetBucket', + ) + bucket_type: 'FacetBucketType' = proto.Field( + proto.ENUM, + number=4, + enum='FacetBucketType', + ) + fetch_matched_annotations: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class IngestAssetRequest(proto.Message): + r"""Request message for IngestAsset API. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + config (google.cloud.visionai_v1.types.IngestAssetRequest.Config): + Provides information for the data and the asset resource + name that the data belongs to. The first + ``IngestAssetRequest`` message must only contain a + ``Config`` message. + + This field is a member of `oneof`_ ``streaming_request``. + time_indexed_data (google.cloud.visionai_v1.types.IngestAssetRequest.TimeIndexedData): + Data to be ingested. + + This field is a member of `oneof`_ ``streaming_request``. + """ + + class Config(proto.Message): + r"""Configuration for the data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + video_type (google.cloud.visionai_v1.types.IngestAssetRequest.Config.VideoType): + Type information for video data. + + This field is a member of `oneof`_ ``data_type``. + asset (str): + Required. The resource name of the asset that + the ingested data belongs to. + """ + + class VideoType(proto.Message): + r"""Type information for video data. + + Attributes: + container_format (google.cloud.visionai_v1.types.IngestAssetRequest.Config.VideoType.ContainerFormat): + Container format of the video data. + """ + class ContainerFormat(proto.Enum): + r"""Container format of the video. + + Values: + CONTAINER_FORMAT_UNSPECIFIED (0): + The default type, not supposed to be used. + CONTAINER_FORMAT_MP4 (1): + Mp4 container format. + """ + CONTAINER_FORMAT_UNSPECIFIED = 0 + CONTAINER_FORMAT_MP4 = 1 + + container_format: 'IngestAssetRequest.Config.VideoType.ContainerFormat' = proto.Field( + proto.ENUM, + number=1, + enum='IngestAssetRequest.Config.VideoType.ContainerFormat', + ) + + video_type: 'IngestAssetRequest.Config.VideoType' = proto.Field( + proto.MESSAGE, + number=2, + oneof='data_type', + message='IngestAssetRequest.Config.VideoType', + ) + asset: str = proto.Field( + proto.STRING, + number=1, + ) + + class TimeIndexedData(proto.Message): + r"""Contains the data and the corresponding time range this data + is for. + + Attributes: + data (bytes): + Data to be ingested. + temporal_partition (google.cloud.visionai_v1.types.Partition.TemporalPartition): + Time range of the data. + """ + + data: bytes = proto.Field( + proto.BYTES, + number=1, + ) + temporal_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + + config: Config = proto.Field( + proto.MESSAGE, + number=1, + oneof='streaming_request', + message=Config, + ) + time_indexed_data: TimeIndexedData = proto.Field( + proto.MESSAGE, + number=2, + oneof='streaming_request', + message=TimeIndexedData, + ) + + +class IngestAssetResponse(proto.Message): + r"""Response message for IngestAsset API. + + Attributes: + successfully_ingested_partition (google.cloud.visionai_v1.types.Partition.TemporalPartition): + Time range of the data that has been + successfully ingested. + """ + + successfully_ingested_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=1, + message='Partition.TemporalPartition', + ) + + +class ClipAssetRequest(proto.Message): + r"""Request message for ClipAsset API. + + Attributes: + name (str): + Required. The resource name of the asset to request clips + for. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + temporal_partition (google.cloud.visionai_v1.types.Partition.TemporalPartition): + Required. The time range to request clips + for. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + temporal_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + + +class ClipAssetResponse(proto.Message): + r"""Response message for ClipAsset API. + + Attributes: + time_indexed_uris (MutableSequence[google.cloud.visionai_v1.types.ClipAssetResponse.TimeIndexedUri]): + A list of signed uris to download the video + clips that cover the requested time range + ordered by time. + """ + + class TimeIndexedUri(proto.Message): + r"""Signed uri with corresponding time range. + + Attributes: + temporal_partition (google.cloud.visionai_v1.types.Partition.TemporalPartition): + Time range of the video that the uri is for. + uri (str): + Signed uri to download the video clip. + """ + + temporal_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=1, + message='Partition.TemporalPartition', + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + time_indexed_uris: MutableSequence[TimeIndexedUri] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=TimeIndexedUri, + ) + + +class GenerateHlsUriRequest(proto.Message): + r"""Request message for GenerateHlsUri API. + + Attributes: + name (str): + Required. The resource name of the asset to request clips + for. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + temporal_partitions (MutableSequence[google.cloud.visionai_v1.types.Partition.TemporalPartition]): + The time range to request clips for. Will be ignored if + ``get_live_view`` is set to True. The total time range + requested should be smaller than 24h. + live_view_enabled (bool): + Option to exclusively show a livestream of + the asset with up to 3 minutes of backlog data. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + temporal_partitions: MutableSequence['Partition.TemporalPartition'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + live_view_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GenerateHlsUriResponse(proto.Message): + r"""Response message for GenerateHlsUri API. + + Attributes: + uri (str): + A signed uri to download the HLS manifest + corresponding to the requested times. + temporal_partitions (MutableSequence[google.cloud.visionai_v1.types.Partition.TemporalPartition]): + A list of temporal partitions of the content + returned in the order they appear in the stream. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + temporal_partitions: MutableSequence['Partition.TemporalPartition'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + + +class SearchAssetsRequest(proto.Message): + r"""Request message for SearchAssets. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + schema_key_sorting_strategy (google.cloud.visionai_v1.types.SchemaKeySortingStrategy): + Sort by the value under the data schema key. + + This field is a member of `oneof`_ ``sort_spec``. + corpus (str): + Required. The parent corpus to search. Format: + \`projects/{project_id}/locations/{location_id}/corpora/{corpus_id}' + page_size (int): + The number of results to be returned in this page. If it's + 0, the server will decide the appropriate page_size. + page_token (str): + The continuation token to fetch the next + page. If empty, it means it is fetching the + first page. + content_time_ranges (google.cloud.visionai_v1.types.DateTimeRangeArray): + Time ranges that matching video content must fall within. If + no ranges are provided, there will be no time restriction. + This field is treated just like the criteria below, but + defined separately for convenience as it is used frequently. + Note that if the end_time is in the future, it will be + clamped to the time the request was received. + criteria (MutableSequence[google.cloud.visionai_v1.types.Criteria]): + Criteria applied to search results. + facet_selections (MutableSequence[google.cloud.visionai_v1.types.FacetGroup]): + Stores most recent facet selection state. + Only facet groups with user's selection will be + presented here. Selection state is either + selected or unselected. Only selected facet + buckets will be used as search criteria. + result_annotation_keys (MutableSequence[str]): + A list of annotation keys to specify the annotations to be + retrieved and returned with each search result. Annotation + granularity must be GRANULARITY_ASSET_LEVEL and its search + strategy must not be NO_SEARCH. + search_query (str): + Global search query. Allows user to search + assets without needing to specify which field + the value belongs to. + """ + + schema_key_sorting_strategy: 'SchemaKeySortingStrategy' = proto.Field( + proto.MESSAGE, + number=9, + oneof='sort_spec', + message='SchemaKeySortingStrategy', + ) + corpus: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + content_time_ranges: 'DateTimeRangeArray' = proto.Field( + proto.MESSAGE, + number=5, + message='DateTimeRangeArray', + ) + criteria: MutableSequence['Criteria'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Criteria', + ) + facet_selections: MutableSequence['FacetGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='FacetGroup', + ) + result_annotation_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + search_query: str = proto.Field( + proto.STRING, + number=10, + ) + + +class SearchIndexEndpointRequest(proto.Message): + r"""Request message for SearchIndexEndpoint. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image_query (google.cloud.visionai_v1.types.ImageQuery): + An image-only query. + + This field is a member of `oneof`_ ``query``. + text_query (str): + A text-only query. + + This field is a member of `oneof`_ ``query``. + index_endpoint (str): + Required. The index endpoint to search. Format: + \`projects/{project_id}/locations/{location_id}/indexEndpoints/{index_endpoint_id}' + criteria (MutableSequence[google.cloud.visionai_v1.types.Criteria]): + Criteria applied to search results. + exclusion_criteria (MutableSequence[google.cloud.visionai_v1.types.Criteria]): + Criteria to exclude from search results. Note that + ``fetch_matched_annotations`` will be ignored. + page_size (int): + Requested page size. API may return fewer results than + requested. If negative, INVALID_ARGUMENT error will be + returned. If unspecified or 0, API will pick a default size, + which is 10. If the requested page size is larger than the + maximum size, API will pick the maximum size, which is 100. + page_token (str): + The continuation token to fetch the next + page. If empty, it means it is fetching the + first page. + """ + + image_query: 'ImageQuery' = proto.Field( + proto.MESSAGE, + number=2, + oneof='query', + message='ImageQuery', + ) + text_query: str = proto.Field( + proto.STRING, + number=3, + oneof='query', + ) + index_endpoint: str = proto.Field( + proto.STRING, + number=1, + ) + criteria: MutableSequence['Criteria'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Criteria', + ) + exclusion_criteria: MutableSequence['Criteria'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Criteria', + ) + page_size: int = proto.Field( + proto.INT32, + number=5, + ) + page_token: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ImageQuery(proto.Message): + r"""Image query for search endpoint request. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + input_image (bytes): + Input image in raw bytes. + + This field is a member of `oneof`_ ``image``. + asset (str): + Resource name of the asset. Only supported in IMAGE corpus + type. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + + This field is a member of `oneof`_ ``image``. + """ + + input_image: bytes = proto.Field( + proto.BYTES, + number=1, + oneof='image', + ) + asset: str = proto.Field( + proto.STRING, + number=2, + oneof='image', + ) + + +class SchemaKeySortingStrategy(proto.Message): + r"""A strategy to specify how to sort by data schema key. + + Attributes: + options (MutableSequence[google.cloud.visionai_v1.types.SchemaKeySortingStrategy.Option]): + Options in the front have high priority than + those in the back. + """ + + class Option(proto.Message): + r"""Option for one data schema key. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + data_schema_key (str): + The data used to sort. + sort_decreasing (bool): + Whether to sort in decreasing order or + increasing order. By default, results are sorted + in incresing order. + aggregate_method (google.cloud.visionai_v1.types.SchemaKeySortingStrategy.Option.AggregateMethod): + Aggregate method for the current data schema + key. + + This field is a member of `oneof`_ ``_aggregate_method``. + """ + class AggregateMethod(proto.Enum): + r"""When one result has multiple values with the same key, specify which + value is used to sort. By default, AGGREGATE_METHOD_LARGEST is used + when results are sorted in decreasing order, + AGGREGATE_METHOD_SMALLEST is used when results are sorted in + incresing order. + + Values: + AGGREGATE_METHOD_UNSPECIFIED (0): + The unspecified aggregate method will be + overwritten as mentioned above. + AGGREGATE_METHOD_LARGEST (1): + Take the (lexicographical or numerical) + largest value to sort. + AGGREGATE_METHOD_SMALLEST (2): + Take the (lexicographical or numerical) + smallest value to sort. + """ + AGGREGATE_METHOD_UNSPECIFIED = 0 + AGGREGATE_METHOD_LARGEST = 1 + AGGREGATE_METHOD_SMALLEST = 2 + + data_schema_key: str = proto.Field( + proto.STRING, + number=1, + ) + sort_decreasing: bool = proto.Field( + proto.BOOL, + number=2, + ) + aggregate_method: 'SchemaKeySortingStrategy.Option.AggregateMethod' = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum='SchemaKeySortingStrategy.Option.AggregateMethod', + ) + + options: MutableSequence[Option] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Option, + ) + + +class DeleteAssetMetadata(proto.Message): + r"""The metadata for DeleteAsset API that embeds in + [metadata][google.longrunning.Operation.metadata] field. + + """ + + +class AnnotationMatchingResult(proto.Message): + r"""Stores the criteria-annotation matching results for each + search result item. + + Attributes: + criteria (google.cloud.visionai_v1.types.Criteria): + The criteria used for matching. It can be an + input search criteria or a criteria converted + from a facet selection. + matched_annotations (MutableSequence[google.cloud.visionai_v1.types.Annotation]): + Matched annotations for the criteria. + status (google.rpc.status_pb2.Status): + Status of the match result. Possible values: + FAILED_PRECONDITION - the criteria is not eligible for + match. OK - matching is performed. + """ + + criteria: 'Criteria' = proto.Field( + proto.MESSAGE, + number=1, + message='Criteria', + ) + matched_annotations: MutableSequence['Annotation'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Annotation', + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + + +class SearchResultItem(proto.Message): + r"""Search result contains asset name and corresponding time + ranges. + + Attributes: + asset (str): + The resource name of the asset. Format: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + segments (MutableSequence[google.cloud.visionai_v1.types.Partition.TemporalPartition]): + The matched asset segments. Deprecated: please use singular + ``segment`` field. + segment (google.cloud.visionai_v1.types.Partition.TemporalPartition): + The matched asset segment. + relevance (float): + Relevance of this ``SearchResultItem`` to user search + request. Currently available only in Image Warehouse, and by + default represents cosine similarity. In the future can be + other measures such as "dot product" or "topicality" + requested in the search request. + requested_annotations (MutableSequence[google.cloud.visionai_v1.types.Annotation]): + Search result annotations specified by + result_annotation_keys in search request. + annotation_matching_results (MutableSequence[google.cloud.visionai_v1.types.AnnotationMatchingResult]): + Criteria or facet-selection based annotation matching + results associated to this search result item. Only contains + results for criteria or facet_selections with + fetch_matched_annotations=true. + """ + + asset: str = proto.Field( + proto.STRING, + number=1, + ) + segments: MutableSequence['Partition.TemporalPartition'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + segment: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=5, + message='Partition.TemporalPartition', + ) + relevance: float = proto.Field( + proto.DOUBLE, + number=6, + ) + requested_annotations: MutableSequence['Annotation'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Annotation', + ) + annotation_matching_results: MutableSequence['AnnotationMatchingResult'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AnnotationMatchingResult', + ) + + +class SearchAssetsResponse(proto.Message): + r"""Response message for SearchAssets. + + Attributes: + search_result_items (MutableSequence[google.cloud.visionai_v1.types.SearchResultItem]): + Returned search results. + next_page_token (str): + The next-page continuation token. + facet_results (MutableSequence[google.cloud.visionai_v1.types.FacetGroup]): + Facet search results of a given query, which + contains user's already-selected facet values + and updated facet search results. + """ + + @property + def raw_page(self): + return self + + search_result_items: MutableSequence['SearchResultItem'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchResultItem', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + facet_results: MutableSequence['FacetGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='FacetGroup', + ) + + +class SearchIndexEndpointResponse(proto.Message): + r"""Response message for SearchIndexEndpoint. + + Attributes: + search_result_items (MutableSequence[google.cloud.visionai_v1.types.SearchResultItem]): + Returned search results. + next_page_token (str): + The next-page continuation token. + If this field is omitted, there are no + subsequent pages. + """ + + @property + def raw_page(self): + return self + + search_result_items: MutableSequence['SearchResultItem'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchResultItem', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class IntRange(proto.Message): + r"""Integer range type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start (int): + Start of the int range. + + This field is a member of `oneof`_ ``_start``. + end (int): + End of the int range. + + This field is a member of `oneof`_ ``_end``. + """ + + start: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + end: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + +class FloatRange(proto.Message): + r"""Float range type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start (float): + Start of the float range. + + This field is a member of `oneof`_ ``_start``. + end (float): + End of the float range. + + This field is a member of `oneof`_ ``_end``. + """ + + start: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + end: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + +class StringArray(proto.Message): + r"""A list of string-type values. + + Attributes: + txt_values (MutableSequence[str]): + String type values. + """ + + txt_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class IntRangeArray(proto.Message): + r"""A list of integer range values. + + Attributes: + int_ranges (MutableSequence[google.cloud.visionai_v1.types.IntRange]): + Int range values. + """ + + int_ranges: MutableSequence['IntRange'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IntRange', + ) + + +class FloatRangeArray(proto.Message): + r"""A list of float range values. + + Attributes: + float_ranges (MutableSequence[google.cloud.visionai_v1.types.FloatRange]): + Float range values. + """ + + float_ranges: MutableSequence['FloatRange'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FloatRange', + ) + + +class DateTimeRange(proto.Message): + r"""Datetime range type. + + Attributes: + start (google.type.datetime_pb2.DateTime): + Start date time. + end (google.type.datetime_pb2.DateTime): + End data time. + """ + + start: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=1, + message=datetime_pb2.DateTime, + ) + end: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=2, + message=datetime_pb2.DateTime, + ) + + +class DateTimeRangeArray(proto.Message): + r"""A list of datetime range values. + + Attributes: + date_time_ranges (MutableSequence[google.cloud.visionai_v1.types.DateTimeRange]): + Date time ranges. + """ + + date_time_ranges: MutableSequence['DateTimeRange'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DateTimeRange', + ) + + +class CircleArea(proto.Message): + r"""Representation of a circle area. + + Attributes: + latitude (float): + Latitude of circle area's center. Degrees [-90 .. 90] + longitude (float): + Longitude of circle area's center. Degrees [-180 .. 180] + radius_meter (float): + Radius of the circle area in meters. + """ + + latitude: float = proto.Field( + proto.DOUBLE, + number=1, + ) + longitude: float = proto.Field( + proto.DOUBLE, + number=2, + ) + radius_meter: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + +class GeoLocationArray(proto.Message): + r"""A list of locations. + + Attributes: + circle_areas (MutableSequence[google.cloud.visionai_v1.types.CircleArea]): + A list of circle areas. + """ + + circle_areas: MutableSequence['CircleArea'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CircleArea', + ) + + +class BoolValue(proto.Message): + r""" + + Attributes: + value (bool): + + """ + + value: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class Criteria(proto.Message): + r"""Filter criteria applied to current search results. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text_array (google.cloud.visionai_v1.types.StringArray): + The text values associated with the field. + + This field is a member of `oneof`_ ``value``. + int_range_array (google.cloud.visionai_v1.types.IntRangeArray): + The integer ranges associated with the field. + + This field is a member of `oneof`_ ``value``. + float_range_array (google.cloud.visionai_v1.types.FloatRangeArray): + The float ranges associated with the field. + + This field is a member of `oneof`_ ``value``. + date_time_range_array (google.cloud.visionai_v1.types.DateTimeRangeArray): + The datetime ranges associated with the + field. + + This field is a member of `oneof`_ ``value``. + geo_location_array (google.cloud.visionai_v1.types.GeoLocationArray): + Geo Location array. + + This field is a member of `oneof`_ ``value``. + bool_value (google.cloud.visionai_v1.types.BoolValue): + A Boolean value. + + This field is a member of `oneof`_ ``value``. + field (str): + The UGA field or ML field to apply filtering + criteria. + fetch_matched_annotations (bool): + If true, return query matched annotations for this criteria. + This option is only applicable for inclusion criteria, i.e., + not exclusion criteria, with partition level annotations. It + supports the following data types: + + - INTEGER + - FLOAT + - STRING (DataSchema.SearchStrategy.EXACT_SEARCH only) + - BOOLEAN + """ + + text_array: 'StringArray' = proto.Field( + proto.MESSAGE, + number=2, + oneof='value', + message='StringArray', + ) + int_range_array: 'IntRangeArray' = proto.Field( + proto.MESSAGE, + number=3, + oneof='value', + message='IntRangeArray', + ) + float_range_array: 'FloatRangeArray' = proto.Field( + proto.MESSAGE, + number=4, + oneof='value', + message='FloatRangeArray', + ) + date_time_range_array: 'DateTimeRangeArray' = proto.Field( + proto.MESSAGE, + number=5, + oneof='value', + message='DateTimeRangeArray', + ) + geo_location_array: 'GeoLocationArray' = proto.Field( + proto.MESSAGE, + number=6, + oneof='value', + message='GeoLocationArray', + ) + bool_value: 'BoolValue' = proto.Field( + proto.MESSAGE, + number=7, + oneof='value', + message='BoolValue', + ) + field: str = proto.Field( + proto.STRING, + number=1, + ) + fetch_matched_annotations: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class Partition(proto.Message): + r"""Partition to specify the partition in time and space for + sub-asset level annotation. + + Attributes: + temporal_partition (google.cloud.visionai_v1.types.Partition.TemporalPartition): + Partition of asset in time. + spatial_partition (google.cloud.visionai_v1.types.Partition.SpatialPartition): + Partition of asset in space. + relative_temporal_partition (google.cloud.visionai_v1.types.Partition.RelativeTemporalPartition): + Partition of asset in time. + """ + + class TemporalPartition(proto.Message): + r"""Partition of asset in UTC Epoch time. Supported by STREAM_VIDEO + corpus type. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of the partition. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the partition. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class SpatialPartition(proto.Message): + r"""Partition of asset in space. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + x_min (int): + The minimum x coordinate value. + + This field is a member of `oneof`_ ``_x_min``. + y_min (int): + The minimum y coordinate value. + + This field is a member of `oneof`_ ``_y_min``. + x_max (int): + The maximum x coordinate value. + + This field is a member of `oneof`_ ``_x_max``. + y_max (int): + The maximum y coordinate value. + + This field is a member of `oneof`_ ``_y_max``. + """ + + x_min: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + y_min: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + x_max: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + y_max: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + + class RelativeTemporalPartition(proto.Message): + r"""Partition of asset in relative time. Supported by VIDEO_ON_DEMAND + corpus type. + + Attributes: + start_offset (google.protobuf.duration_pb2.Duration): + Start time offset of the partition. + end_offset (google.protobuf.duration_pb2.Duration): + End time offset of the partition. + """ + + start_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + temporal_partition: TemporalPartition = proto.Field( + proto.MESSAGE, + number=1, + message=TemporalPartition, + ) + spatial_partition: SpatialPartition = proto.Field( + proto.MESSAGE, + number=2, + message=SpatialPartition, + ) + relative_temporal_partition: RelativeTemporalPartition = proto.Field( + proto.MESSAGE, + number=3, + message=RelativeTemporalPartition, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1/mypy.ini b/owl-bot-staging/google-cloud-visionai/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-visionai/v1/noxfile.py b/owl-bot-staging/google-cloud-visionai/v1/noxfile.py new file mode 100644 index 000000000000..60c4914ee705 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/noxfile.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-visionai' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/visionai_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + +@nox.session(python=ALL_PYTHON[-1]) +def prerelease_deps(session): + """Run the unit test suite against pre-release versions of dependencies.""" + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/visionai_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/snippet_metadata_google.cloud.visionai.v1.json b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/snippet_metadata_google.cloud.visionai.v1.json new file mode 100644 index 000000000000..db06e43868dd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/snippet_metadata_google.cloud.visionai.v1.json @@ -0,0 +1,22354 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.visionai.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-visionai", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.add_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.AddApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "AddApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AddApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "add_application_stream_input" + }, + "description": "Sample for AddApplicationStreamInput", + "file": "visionai_v1_generated_app_platform_add_application_stream_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_AddApplicationStreamInput_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_add_application_stream_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.add_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.AddApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "AddApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AddApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "add_application_stream_input" + }, + "description": "Sample for AddApplicationStreamInput", + "file": "visionai_v1_generated_app_platform_add_application_stream_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_AddApplicationStreamInput_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_add_application_stream_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.create_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_application_instances" + }, + "description": "Sample for CreateApplicationInstances", + "file": "visionai_v1_generated_app_platform_create_application_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateApplicationInstances_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_application_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.create_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_application_instances" + }, + "description": "Sample for CreateApplicationInstances", + "file": "visionai_v1_generated_app_platform_create_application_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateApplicationInstances_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_application_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.create_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateApplicationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1.types.Application" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_application" + }, + "description": "Sample for CreateApplication", + "file": "visionai_v1_generated_app_platform_create_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateApplication_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.create_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateApplicationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1.types.Application" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_application" + }, + "description": "Sample for CreateApplication", + "file": "visionai_v1_generated_app_platform_create_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateApplication_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.create_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateDraftRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1.types.Draft" + }, + { + "name": "draft_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_draft" + }, + "description": "Sample for CreateDraft", + "file": "visionai_v1_generated_app_platform_create_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateDraft_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.create_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateDraftRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1.types.Draft" + }, + { + "name": "draft_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_draft" + }, + "description": "Sample for CreateDraft", + "file": "visionai_v1_generated_app_platform_create_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateDraft_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.create_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1.types.Processor" + }, + { + "name": "processor_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "visionai_v1_generated_app_platform_create_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateProcessor_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.create_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.CreateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1.types.Processor" + }, + { + "name": "processor_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "visionai_v1_generated_app_platform_create_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_CreateProcessor_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_create_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.delete_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_application_instances" + }, + "description": "Sample for DeleteApplicationInstances", + "file": "visionai_v1_generated_app_platform_delete_application_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteApplicationInstances_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_application_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.delete_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_application_instances" + }, + "description": "Sample for DeleteApplicationInstances", + "file": "visionai_v1_generated_app_platform_delete_application_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteApplicationInstances_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_application_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.delete_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_application" + }, + "description": "Sample for DeleteApplication", + "file": "visionai_v1_generated_app_platform_delete_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteApplication_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.delete_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_application" + }, + "description": "Sample for DeleteApplication", + "file": "visionai_v1_generated_app_platform_delete_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteApplication_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.delete_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_draft" + }, + "description": "Sample for DeleteDraft", + "file": "visionai_v1_generated_app_platform_delete_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteDraft_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.delete_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_draft" + }, + "description": "Sample for DeleteDraft", + "file": "visionai_v1_generated_app_platform_delete_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteDraft_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.delete_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "visionai_v1_generated_app_platform_delete_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteProcessor_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.delete_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeleteProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "visionai_v1_generated_app_platform_delete_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeleteProcessor_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_delete_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.deploy_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "deploy_application" + }, + "description": "Sample for DeployApplication", + "file": "visionai_v1_generated_app_platform_deploy_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeployApplication_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_deploy_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.deploy_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.DeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "deploy_application" + }, + "description": "Sample for DeployApplication", + "file": "visionai_v1_generated_app_platform_deploy_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_DeployApplication_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_deploy_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.get_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Application", + "shortName": "get_application" + }, + "description": "Sample for GetApplication", + "file": "visionai_v1_generated_app_platform_get_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetApplication_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.get_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Application", + "shortName": "get_application" + }, + "description": "Sample for GetApplication", + "file": "visionai_v1_generated_app_platform_get_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetApplication_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.get_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Draft", + "shortName": "get_draft" + }, + "description": "Sample for GetDraft", + "file": "visionai_v1_generated_app_platform_get_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetDraft_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.get_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Draft", + "shortName": "get_draft" + }, + "description": "Sample for GetDraft", + "file": "visionai_v1_generated_app_platform_get_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetDraft_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetInstance", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "visionai_v1_generated_app_platform_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetInstance_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.get_instance", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetInstance", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "visionai_v1_generated_app_platform_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetInstance_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.get_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Processor", + "shortName": "get_processor" + }, + "description": "Sample for GetProcessor", + "file": "visionai_v1_generated_app_platform_get_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetProcessor_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.get_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.GetProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Processor", + "shortName": "get_processor" + }, + "description": "Sample for GetProcessor", + "file": "visionai_v1_generated_app_platform_get_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_GetProcessor_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_get_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.list_applications", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListApplications", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListApplications" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListApplicationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListApplicationsAsyncPager", + "shortName": "list_applications" + }, + "description": "Sample for ListApplications", + "file": "visionai_v1_generated_app_platform_list_applications_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListApplications_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_applications_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.list_applications", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListApplications", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListApplications" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListApplicationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListApplicationsPager", + "shortName": "list_applications" + }, + "description": "Sample for ListApplications", + "file": "visionai_v1_generated_app_platform_list_applications_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListApplications_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_applications_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.list_drafts", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListDrafts", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListDrafts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListDraftsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListDraftsAsyncPager", + "shortName": "list_drafts" + }, + "description": "Sample for ListDrafts", + "file": "visionai_v1_generated_app_platform_list_drafts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListDrafts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_drafts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.list_drafts", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListDrafts", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListDrafts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListDraftsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListDraftsPager", + "shortName": "list_drafts" + }, + "description": "Sample for ListDrafts", + "file": "visionai_v1_generated_app_platform_list_drafts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListDrafts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_drafts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "visionai_v1_generated_app_platform_list_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListInstances_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.list_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "visionai_v1_generated_app_platform_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListInstances_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.list_prebuilt_processors", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListPrebuiltProcessors", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListPrebuiltProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListPrebuiltProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ListPrebuiltProcessorsResponse", + "shortName": "list_prebuilt_processors" + }, + "description": "Sample for ListPrebuiltProcessors", + "file": "visionai_v1_generated_app_platform_list_prebuilt_processors_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListPrebuiltProcessors_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_prebuilt_processors_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.list_prebuilt_processors", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListPrebuiltProcessors", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListPrebuiltProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListPrebuiltProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ListPrebuiltProcessorsResponse", + "shortName": "list_prebuilt_processors" + }, + "description": "Sample for ListPrebuiltProcessors", + "file": "visionai_v1_generated_app_platform_list_prebuilt_processors_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListPrebuiltProcessors_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_prebuilt_processors_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.list_processors", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListProcessors", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListProcessorsAsyncPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "visionai_v1_generated_app_platform_list_processors_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListProcessors_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_processors_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.list_processors", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.ListProcessors", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.app_platform.pagers.ListProcessorsPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "visionai_v1_generated_app_platform_list_processors_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_ListProcessors_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_list_processors_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.remove_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.RemoveApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "RemoveApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RemoveApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "remove_application_stream_input" + }, + "description": "Sample for RemoveApplicationStreamInput", + "file": "visionai_v1_generated_app_platform_remove_application_stream_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_RemoveApplicationStreamInput_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_remove_application_stream_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.remove_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.RemoveApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "RemoveApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RemoveApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "remove_application_stream_input" + }, + "description": "Sample for RemoveApplicationStreamInput", + "file": "visionai_v1_generated_app_platform_remove_application_stream_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_RemoveApplicationStreamInput_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_remove_application_stream_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.undeploy_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UndeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UndeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UndeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "undeploy_application" + }, + "description": "Sample for UndeployApplication", + "file": "visionai_v1_generated_app_platform_undeploy_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UndeployApplication_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_undeploy_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.undeploy_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UndeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UndeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UndeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "undeploy_application" + }, + "description": "Sample for UndeployApplication", + "file": "visionai_v1_generated_app_platform_undeploy_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UndeployApplication_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_undeploy_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.update_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "application_instances", + "type": "MutableSequence[google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_application_instances" + }, + "description": "Sample for UpdateApplicationInstances", + "file": "visionai_v1_generated_app_platform_update_application_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateApplicationInstances_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_application_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.update_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "application_instances", + "type": "MutableSequence[google.cloud.visionai_v1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_application_instances" + }, + "description": "Sample for UpdateApplicationInstances", + "file": "visionai_v1_generated_app_platform_update_application_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateApplicationInstances_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_application_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.update_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_application_stream_input" + }, + "description": "Sample for UpdateApplicationStreamInput", + "file": "visionai_v1_generated_app_platform_update_application_stream_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateApplicationStreamInput_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_application_stream_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.update_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_application_stream_input" + }, + "description": "Sample for UpdateApplicationStreamInput", + "file": "visionai_v1_generated_app_platform_update_application_stream_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateApplicationStreamInput_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_application_stream_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.update_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateApplicationRequest" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1.types.Application" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_application" + }, + "description": "Sample for UpdateApplication", + "file": "visionai_v1_generated_app_platform_update_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateApplication_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.update_application", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateApplication", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateApplicationRequest" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1.types.Application" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_application" + }, + "description": "Sample for UpdateApplication", + "file": "visionai_v1_generated_app_platform_update_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateApplication_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.update_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateDraftRequest" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1.types.Draft" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_draft" + }, + "description": "Sample for UpdateDraft", + "file": "visionai_v1_generated_app_platform_update_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateDraft_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.update_draft", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateDraft", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateDraftRequest" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1.types.Draft" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_draft" + }, + "description": "Sample for UpdateDraft", + "file": "visionai_v1_generated_app_platform_update_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateDraft_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformAsyncClient.update_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateProcessorRequest" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1.types.Processor" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_processor" + }, + "description": "Sample for UpdateProcessor", + "file": "visionai_v1_generated_app_platform_update_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateProcessor_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1.AppPlatformClient.update_processor", + "method": { + "fullName": "google.cloud.visionai.v1.AppPlatform.UpdateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateProcessorRequest" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1.types.Processor" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_processor" + }, + "description": "Sample for UpdateProcessor", + "file": "visionai_v1_generated_app_platform_update_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_AppPlatform_UpdateProcessor_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_app_platform_update_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.HealthCheckServiceAsyncClient", + "shortName": "HealthCheckServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.HealthCheckServiceAsyncClient.health_check", + "method": { + "fullName": "google.cloud.visionai.v1.HealthCheckService.HealthCheck", + "service": { + "fullName": "google.cloud.visionai.v1.HealthCheckService", + "shortName": "HealthCheckService" + }, + "shortName": "HealthCheck" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.HealthCheckRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.HealthCheckResponse", + "shortName": "health_check" + }, + "description": "Sample for HealthCheck", + "file": "visionai_v1_generated_health_check_service_health_check_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_HealthCheckService_HealthCheck_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_health_check_service_health_check_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.HealthCheckServiceClient", + "shortName": "HealthCheckServiceClient" + }, + "fullName": "google.cloud.visionai_v1.HealthCheckServiceClient.health_check", + "method": { + "fullName": "google.cloud.visionai.v1.HealthCheckService.HealthCheck", + "service": { + "fullName": "google.cloud.visionai.v1.HealthCheckService", + "shortName": "HealthCheckService" + }, + "shortName": "HealthCheck" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.HealthCheckRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.HealthCheckResponse", + "shortName": "health_check" + }, + "description": "Sample for HealthCheck", + "file": "visionai_v1_generated_health_check_service_health_check_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_HealthCheckService_HealthCheck_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_health_check_service_health_check_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.batch_run_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.BatchRunProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "BatchRunProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.BatchRunProcessRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.visionai_v1.types.CreateProcessRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_run_process" + }, + "description": "Sample for BatchRunProcess", + "file": "visionai_v1_generated_live_video_analytics_batch_run_process_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_BatchRunProcess_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_batch_run_process_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.batch_run_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.BatchRunProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "BatchRunProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.BatchRunProcessRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.visionai_v1.types.CreateProcessRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_run_process" + }, + "description": "Sample for BatchRunProcess", + "file": "visionai_v1_generated_live_video_analytics_batch_run_process_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_BatchRunProcess_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_batch_run_process_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.create_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.CreateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateAnalysisRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1.types.Analysis" + }, + { + "name": "analysis_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_analysis" + }, + "description": "Sample for CreateAnalysis", + "file": "visionai_v1_generated_live_video_analytics_create_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_CreateAnalysis_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_create_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.create_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.CreateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateAnalysisRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1.types.Analysis" + }, + { + "name": "analysis_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_analysis" + }, + "description": "Sample for CreateAnalysis", + "file": "visionai_v1_generated_live_video_analytics_create_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_CreateAnalysis_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_create_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.create_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.CreateOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateOperatorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "operator", + "type": "google.cloud.visionai_v1.types.Operator" + }, + { + "name": "operator_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_operator" + }, + "description": "Sample for CreateOperator", + "file": "visionai_v1_generated_live_video_analytics_create_operator_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_CreateOperator_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_create_operator_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.create_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.CreateOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateOperatorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "operator", + "type": "google.cloud.visionai_v1.types.Operator" + }, + { + "name": "operator_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_operator" + }, + "description": "Sample for CreateOperator", + "file": "visionai_v1_generated_live_video_analytics_create_operator_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_CreateOperator_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_create_operator_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.create_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.CreateProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateProcessRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "process", + "type": "google.cloud.visionai_v1.types.Process" + }, + { + "name": "process_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_process" + }, + "description": "Sample for CreateProcess", + "file": "visionai_v1_generated_live_video_analytics_create_process_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_CreateProcess_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_create_process_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.create_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.CreateProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateProcessRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "process", + "type": "google.cloud.visionai_v1.types.Process" + }, + { + "name": "process_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_process" + }, + "description": "Sample for CreateProcess", + "file": "visionai_v1_generated_live_video_analytics_create_process_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_CreateProcess_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_create_process_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.delete_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.DeleteAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_analysis" + }, + "description": "Sample for DeleteAnalysis", + "file": "visionai_v1_generated_live_video_analytics_delete_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_DeleteAnalysis_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_delete_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.delete_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.DeleteAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_analysis" + }, + "description": "Sample for DeleteAnalysis", + "file": "visionai_v1_generated_live_video_analytics_delete_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_DeleteAnalysis_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_delete_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.delete_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.DeleteOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteOperatorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_operator" + }, + "description": "Sample for DeleteOperator", + "file": "visionai_v1_generated_live_video_analytics_delete_operator_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_DeleteOperator_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_delete_operator_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.delete_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.DeleteOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteOperatorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_operator" + }, + "description": "Sample for DeleteOperator", + "file": "visionai_v1_generated_live_video_analytics_delete_operator_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_DeleteOperator_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_delete_operator_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.delete_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.DeleteProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteProcessRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_process" + }, + "description": "Sample for DeleteProcess", + "file": "visionai_v1_generated_live_video_analytics_delete_process_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_DeleteProcess_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_delete_process_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.delete_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.DeleteProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteProcessRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_process" + }, + "description": "Sample for DeleteProcess", + "file": "visionai_v1_generated_live_video_analytics_delete_process_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_DeleteProcess_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_delete_process_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.get_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.GetAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Analysis", + "shortName": "get_analysis" + }, + "description": "Sample for GetAnalysis", + "file": "visionai_v1_generated_live_video_analytics_get_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_GetAnalysis_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_get_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.get_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.GetAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Analysis", + "shortName": "get_analysis" + }, + "description": "Sample for GetAnalysis", + "file": "visionai_v1_generated_live_video_analytics_get_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_GetAnalysis_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_get_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.get_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.GetOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetOperatorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Operator", + "shortName": "get_operator" + }, + "description": "Sample for GetOperator", + "file": "visionai_v1_generated_live_video_analytics_get_operator_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_GetOperator_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_get_operator_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.get_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.GetOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetOperatorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Operator", + "shortName": "get_operator" + }, + "description": "Sample for GetOperator", + "file": "visionai_v1_generated_live_video_analytics_get_operator_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_GetOperator_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_get_operator_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.get_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.GetProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetProcessRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Process", + "shortName": "get_process" + }, + "description": "Sample for GetProcess", + "file": "visionai_v1_generated_live_video_analytics_get_process_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_GetProcess_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_get_process_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.get_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.GetProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetProcessRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Process", + "shortName": "get_process" + }, + "description": "Sample for GetProcess", + "file": "visionai_v1_generated_live_video_analytics_get_process_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_GetProcess_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_get_process_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.list_analyses", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListAnalyses", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListAnalyses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListAnalysesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListAnalysesAsyncPager", + "shortName": "list_analyses" + }, + "description": "Sample for ListAnalyses", + "file": "visionai_v1_generated_live_video_analytics_list_analyses_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListAnalyses_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_analyses_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.list_analyses", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListAnalyses", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListAnalyses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListAnalysesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListAnalysesPager", + "shortName": "list_analyses" + }, + "description": "Sample for ListAnalyses", + "file": "visionai_v1_generated_live_video_analytics_list_analyses_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListAnalyses_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_analyses_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.list_operators", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListOperators", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListOperators" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListOperatorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListOperatorsAsyncPager", + "shortName": "list_operators" + }, + "description": "Sample for ListOperators", + "file": "visionai_v1_generated_live_video_analytics_list_operators_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListOperators_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_operators_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.list_operators", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListOperators", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListOperators" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListOperatorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListOperatorsPager", + "shortName": "list_operators" + }, + "description": "Sample for ListOperators", + "file": "visionai_v1_generated_live_video_analytics_list_operators_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListOperators_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_operators_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.list_processes", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListProcesses", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListProcesses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListProcessesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListProcessesAsyncPager", + "shortName": "list_processes" + }, + "description": "Sample for ListProcesses", + "file": "visionai_v1_generated_live_video_analytics_list_processes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListProcesses_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_processes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.list_processes", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListProcesses", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListProcesses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListProcessesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListProcessesPager", + "shortName": "list_processes" + }, + "description": "Sample for ListProcesses", + "file": "visionai_v1_generated_live_video_analytics_list_processes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListProcesses_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_processes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.list_public_operators", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListPublicOperators", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListPublicOperators" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListPublicOperatorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListPublicOperatorsAsyncPager", + "shortName": "list_public_operators" + }, + "description": "Sample for ListPublicOperators", + "file": "visionai_v1_generated_live_video_analytics_list_public_operators_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListPublicOperators_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_public_operators_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.list_public_operators", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ListPublicOperators", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListPublicOperators" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListPublicOperatorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.live_video_analytics.pagers.ListPublicOperatorsPager", + "shortName": "list_public_operators" + }, + "description": "Sample for ListPublicOperators", + "file": "visionai_v1_generated_live_video_analytics_list_public_operators_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ListPublicOperators_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_list_public_operators_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.resolve_operator_info", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ResolveOperatorInfo", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ResolveOperatorInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ResolveOperatorInfoRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "queries", + "type": "MutableSequence[google.cloud.visionai_v1.types.OperatorQuery]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ResolveOperatorInfoResponse", + "shortName": "resolve_operator_info" + }, + "description": "Sample for ResolveOperatorInfo", + "file": "visionai_v1_generated_live_video_analytics_resolve_operator_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ResolveOperatorInfo_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_resolve_operator_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.resolve_operator_info", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.ResolveOperatorInfo", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ResolveOperatorInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ResolveOperatorInfoRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "queries", + "type": "MutableSequence[google.cloud.visionai_v1.types.OperatorQuery]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ResolveOperatorInfoResponse", + "shortName": "resolve_operator_info" + }, + "description": "Sample for ResolveOperatorInfo", + "file": "visionai_v1_generated_live_video_analytics_resolve_operator_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_ResolveOperatorInfo_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_resolve_operator_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.update_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.UpdateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateAnalysisRequest" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1.types.Analysis" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_analysis" + }, + "description": "Sample for UpdateAnalysis", + "file": "visionai_v1_generated_live_video_analytics_update_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_UpdateAnalysis_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_update_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.update_analysis", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.UpdateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateAnalysisRequest" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1.types.Analysis" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_analysis" + }, + "description": "Sample for UpdateAnalysis", + "file": "visionai_v1_generated_live_video_analytics_update_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_UpdateAnalysis_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_update_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.update_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.UpdateOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateOperatorRequest" + }, + { + "name": "operator", + "type": "google.cloud.visionai_v1.types.Operator" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_operator" + }, + "description": "Sample for UpdateOperator", + "file": "visionai_v1_generated_live_video_analytics_update_operator_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_UpdateOperator_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_update_operator_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.update_operator", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.UpdateOperator", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateOperator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateOperatorRequest" + }, + { + "name": "operator", + "type": "google.cloud.visionai_v1.types.Operator" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_operator" + }, + "description": "Sample for UpdateOperator", + "file": "visionai_v1_generated_live_video_analytics_update_operator_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_UpdateOperator_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_update_operator_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsAsyncClient.update_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.UpdateProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateProcessRequest" + }, + { + "name": "process", + "type": "google.cloud.visionai_v1.types.Process" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_process" + }, + "description": "Sample for UpdateProcess", + "file": "visionai_v1_generated_live_video_analytics_update_process_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_UpdateProcess_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_update_process_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1.LiveVideoAnalyticsClient.update_process", + "method": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics.UpdateProcess", + "service": { + "fullName": "google.cloud.visionai.v1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateProcess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateProcessRequest" + }, + { + "name": "process", + "type": "google.cloud.visionai_v1.types.Process" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_process" + }, + "description": "Sample for UpdateProcess", + "file": "visionai_v1_generated_live_video_analytics_update_process_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_LiveVideoAnalytics_UpdateProcess_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_live_video_analytics_update_process_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient.acquire_lease", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.AcquireLease", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "AcquireLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AcquireLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Lease", + "shortName": "acquire_lease" + }, + "description": "Sample for AcquireLease", + "file": "visionai_v1_generated_streaming_service_acquire_lease_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_AcquireLease_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_acquire_lease_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceClient.acquire_lease", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.AcquireLease", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "AcquireLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AcquireLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Lease", + "shortName": "acquire_lease" + }, + "description": "Sample for AcquireLease", + "file": "visionai_v1_generated_streaming_service_acquire_lease_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_AcquireLease_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_acquire_lease_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient.receive_events", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.ReceiveEvents", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceiveEvents" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.ReceiveEventsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.ReceiveEventsResponse]", + "shortName": "receive_events" + }, + "description": "Sample for ReceiveEvents", + "file": "visionai_v1_generated_streaming_service_receive_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_ReceiveEvents_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_receive_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceClient.receive_events", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.ReceiveEvents", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceiveEvents" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.ReceiveEventsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.ReceiveEventsResponse]", + "shortName": "receive_events" + }, + "description": "Sample for ReceiveEvents", + "file": "visionai_v1_generated_streaming_service_receive_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_ReceiveEvents_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_receive_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient.receive_packets", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.ReceivePackets", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceivePackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.ReceivePacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.ReceivePacketsResponse]", + "shortName": "receive_packets" + }, + "description": "Sample for ReceivePackets", + "file": "visionai_v1_generated_streaming_service_receive_packets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_ReceivePackets_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_receive_packets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceClient.receive_packets", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.ReceivePackets", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceivePackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.ReceivePacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.ReceivePacketsResponse]", + "shortName": "receive_packets" + }, + "description": "Sample for ReceivePackets", + "file": "visionai_v1_generated_streaming_service_receive_packets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_ReceivePackets_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_receive_packets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient.release_lease", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.ReleaseLease", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReleaseLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ReleaseLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ReleaseLeaseResponse", + "shortName": "release_lease" + }, + "description": "Sample for ReleaseLease", + "file": "visionai_v1_generated_streaming_service_release_lease_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_ReleaseLease_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_release_lease_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceClient.release_lease", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.ReleaseLease", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReleaseLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ReleaseLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ReleaseLeaseResponse", + "shortName": "release_lease" + }, + "description": "Sample for ReleaseLease", + "file": "visionai_v1_generated_streaming_service_release_lease_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_ReleaseLease_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_release_lease_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient.renew_lease", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.RenewLease", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "RenewLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RenewLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Lease", + "shortName": "renew_lease" + }, + "description": "Sample for RenewLease", + "file": "visionai_v1_generated_streaming_service_renew_lease_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_RenewLease_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_renew_lease_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceClient.renew_lease", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.RenewLease", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "RenewLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RenewLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Lease", + "shortName": "renew_lease" + }, + "description": "Sample for RenewLease", + "file": "visionai_v1_generated_streaming_service_renew_lease_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_RenewLease_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_renew_lease_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceAsyncClient.send_packets", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.SendPackets", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "SendPackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.SendPacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.SendPacketsResponse]", + "shortName": "send_packets" + }, + "description": "Sample for SendPackets", + "file": "visionai_v1_generated_streaming_service_send_packets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_SendPackets_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_send_packets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamingServiceClient.send_packets", + "method": { + "fullName": "google.cloud.visionai.v1.StreamingService.SendPackets", + "service": { + "fullName": "google.cloud.visionai.v1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "SendPackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.SendPacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.SendPacketsResponse]", + "shortName": "send_packets" + }, + "description": "Sample for SendPackets", + "file": "visionai_v1_generated_streaming_service_send_packets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamingService_SendPackets_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streaming_service_send_packets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.create_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1.types.Cluster" + }, + { + "name": "cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_cluster" + }, + "description": "Sample for CreateCluster", + "file": "visionai_v1_generated_streams_service_create_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateCluster_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.create_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1.types.Cluster" + }, + { + "name": "cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_cluster" + }, + "description": "Sample for CreateCluster", + "file": "visionai_v1_generated_streams_service_create_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateCluster_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.create_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1.types.Event" + }, + { + "name": "event_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_event" + }, + "description": "Sample for CreateEvent", + "file": "visionai_v1_generated_streams_service_create_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateEvent_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.create_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1.types.Event" + }, + { + "name": "event_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_event" + }, + "description": "Sample for CreateEvent", + "file": "visionai_v1_generated_streams_service_create_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateEvent_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.create_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1.types.Series" + }, + { + "name": "series_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_series" + }, + "description": "Sample for CreateSeries", + "file": "visionai_v1_generated_streams_service_create_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateSeries_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.create_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1.types.Series" + }, + { + "name": "series_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_series" + }, + "description": "Sample for CreateSeries", + "file": "visionai_v1_generated_streams_service_create_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateSeries_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.create_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateStreamRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1.types.Stream" + }, + { + "name": "stream_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_stream" + }, + "description": "Sample for CreateStream", + "file": "visionai_v1_generated_streams_service_create_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateStream_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.create_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.CreateStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateStreamRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1.types.Stream" + }, + { + "name": "stream_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_stream" + }, + "description": "Sample for CreateStream", + "file": "visionai_v1_generated_streams_service_create_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_CreateStream_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_create_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.delete_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "visionai_v1_generated_streams_service_delete_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteCluster_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.delete_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "visionai_v1_generated_streams_service_delete_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteCluster_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.delete_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_event" + }, + "description": "Sample for DeleteEvent", + "file": "visionai_v1_generated_streams_service_delete_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteEvent_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.delete_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_event" + }, + "description": "Sample for DeleteEvent", + "file": "visionai_v1_generated_streams_service_delete_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteEvent_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.delete_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_series" + }, + "description": "Sample for DeleteSeries", + "file": "visionai_v1_generated_streams_service_delete_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteSeries_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.delete_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_series" + }, + "description": "Sample for DeleteSeries", + "file": "visionai_v1_generated_streams_service_delete_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteSeries_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.delete_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_stream" + }, + "description": "Sample for DeleteStream", + "file": "visionai_v1_generated_streams_service_delete_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteStream_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.delete_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.DeleteStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_stream" + }, + "description": "Sample for DeleteStream", + "file": "visionai_v1_generated_streams_service_delete_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_DeleteStream_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_delete_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.generate_stream_hls_token", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GenerateStreamHlsToken", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GenerateStreamHlsToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GenerateStreamHlsTokenRequest" + }, + { + "name": "stream", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.GenerateStreamHlsTokenResponse", + "shortName": "generate_stream_hls_token" + }, + "description": "Sample for GenerateStreamHlsToken", + "file": "visionai_v1_generated_streams_service_generate_stream_hls_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GenerateStreamHlsToken_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_generate_stream_hls_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.generate_stream_hls_token", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GenerateStreamHlsToken", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GenerateStreamHlsToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GenerateStreamHlsTokenRequest" + }, + { + "name": "stream", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.GenerateStreamHlsTokenResponse", + "shortName": "generate_stream_hls_token" + }, + "description": "Sample for GenerateStreamHlsToken", + "file": "visionai_v1_generated_streams_service_generate_stream_hls_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GenerateStreamHlsToken_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_generate_stream_hls_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.get_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "visionai_v1_generated_streams_service_get_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetCluster_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.get_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "visionai_v1_generated_streams_service_get_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetCluster_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.get_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Event", + "shortName": "get_event" + }, + "description": "Sample for GetEvent", + "file": "visionai_v1_generated_streams_service_get_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetEvent_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.get_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Event", + "shortName": "get_event" + }, + "description": "Sample for GetEvent", + "file": "visionai_v1_generated_streams_service_get_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetEvent_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.get_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Series", + "shortName": "get_series" + }, + "description": "Sample for GetSeries", + "file": "visionai_v1_generated_streams_service_get_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetSeries_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.get_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Series", + "shortName": "get_series" + }, + "description": "Sample for GetSeries", + "file": "visionai_v1_generated_streams_service_get_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetSeries_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.get_stream_thumbnail", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetStreamThumbnail", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetStreamThumbnail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetStreamThumbnailRequest" + }, + { + "name": "stream", + "type": "str" + }, + { + "name": "gcs_object_name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "get_stream_thumbnail" + }, + "description": "Sample for GetStreamThumbnail", + "file": "visionai_v1_generated_streams_service_get_stream_thumbnail_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetStreamThumbnail_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_stream_thumbnail_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.get_stream_thumbnail", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetStreamThumbnail", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetStreamThumbnail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetStreamThumbnailRequest" + }, + { + "name": "stream", + "type": "str" + }, + { + "name": "gcs_object_name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "get_stream_thumbnail" + }, + "description": "Sample for GetStreamThumbnail", + "file": "visionai_v1_generated_streams_service_get_stream_thumbnail_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetStreamThumbnail_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_stream_thumbnail_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.get_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Stream", + "shortName": "get_stream" + }, + "description": "Sample for GetStream", + "file": "visionai_v1_generated_streams_service_get_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetStream_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.get_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.GetStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Stream", + "shortName": "get_stream" + }, + "description": "Sample for GetStream", + "file": "visionai_v1_generated_streams_service_get_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_GetStream_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_get_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.list_clusters", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListClusters", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListClustersAsyncPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "visionai_v1_generated_streams_service_list_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListClusters_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.list_clusters", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListClusters", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListClustersPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "visionai_v1_generated_streams_service_list_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListClusters_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.list_events", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListEvents", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListEventsAsyncPager", + "shortName": "list_events" + }, + "description": "Sample for ListEvents", + "file": "visionai_v1_generated_streams_service_list_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListEvents_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.list_events", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListEvents", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListEventsPager", + "shortName": "list_events" + }, + "description": "Sample for ListEvents", + "file": "visionai_v1_generated_streams_service_list_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListEvents_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.list_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListSeriesAsyncPager", + "shortName": "list_series" + }, + "description": "Sample for ListSeries", + "file": "visionai_v1_generated_streams_service_list_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListSeries_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.list_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListSeriesPager", + "shortName": "list_series" + }, + "description": "Sample for ListSeries", + "file": "visionai_v1_generated_streams_service_list_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListSeries_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.list_streams", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListStreams", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListStreams" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListStreamsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListStreamsAsyncPager", + "shortName": "list_streams" + }, + "description": "Sample for ListStreams", + "file": "visionai_v1_generated_streams_service_list_streams_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListStreams_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_streams_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.list_streams", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.ListStreams", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListStreams" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListStreamsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.streams_service.pagers.ListStreamsPager", + "shortName": "list_streams" + }, + "description": "Sample for ListStreams", + "file": "visionai_v1_generated_streams_service_list_streams_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_ListStreams_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_list_streams_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.materialize_channel", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.MaterializeChannel", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "MaterializeChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.MaterializeChannelRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel", + "type": "google.cloud.visionai_v1.types.Channel" + }, + { + "name": "channel_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "materialize_channel" + }, + "description": "Sample for MaterializeChannel", + "file": "visionai_v1_generated_streams_service_materialize_channel_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_MaterializeChannel_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_materialize_channel_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.materialize_channel", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.MaterializeChannel", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "MaterializeChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.MaterializeChannelRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel", + "type": "google.cloud.visionai_v1.types.Channel" + }, + { + "name": "channel_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "materialize_channel" + }, + "description": "Sample for MaterializeChannel", + "file": "visionai_v1_generated_streams_service_materialize_channel_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_MaterializeChannel_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_materialize_channel_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.update_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1.types.Cluster" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "visionai_v1_generated_streams_service_update_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateCluster_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.update_cluster", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateCluster", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1.types.Cluster" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "visionai_v1_generated_streams_service_update_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateCluster_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.update_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateEventRequest" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1.types.Event" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_event" + }, + "description": "Sample for UpdateEvent", + "file": "visionai_v1_generated_streams_service_update_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateEvent_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.update_event", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateEvent", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateEventRequest" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1.types.Event" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_event" + }, + "description": "Sample for UpdateEvent", + "file": "visionai_v1_generated_streams_service_update_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateEvent_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.update_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateSeriesRequest" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1.types.Series" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_series" + }, + "description": "Sample for UpdateSeries", + "file": "visionai_v1_generated_streams_service_update_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateSeries_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.update_series", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateSeries", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateSeriesRequest" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1.types.Series" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_series" + }, + "description": "Sample for UpdateSeries", + "file": "visionai_v1_generated_streams_service_update_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateSeries_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceAsyncClient.update_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateStreamRequest" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1.types.Stream" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_stream" + }, + "description": "Sample for UpdateStream", + "file": "visionai_v1_generated_streams_service_update_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateStream_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1.StreamsServiceClient.update_stream", + "method": { + "fullName": "google.cloud.visionai.v1.StreamsService.UpdateStream", + "service": { + "fullName": "google.cloud.visionai.v1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateStreamRequest" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1.types.Stream" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_stream" + }, + "description": "Sample for UpdateStream", + "file": "visionai_v1_generated_streams_service_update_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_StreamsService_UpdateStream_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_streams_service_update_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.add_collection_item", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.AddCollectionItem", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "AddCollectionItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AddCollectionItemRequest" + }, + { + "name": "item", + "type": "google.cloud.visionai_v1.types.CollectionItem" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.AddCollectionItemResponse", + "shortName": "add_collection_item" + }, + "description": "Sample for AddCollectionItem", + "file": "visionai_v1_generated_warehouse_add_collection_item_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_AddCollectionItem_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_add_collection_item_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.add_collection_item", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.AddCollectionItem", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "AddCollectionItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AddCollectionItemRequest" + }, + { + "name": "item", + "type": "google.cloud.visionai_v1.types.CollectionItem" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.AddCollectionItemResponse", + "shortName": "add_collection_item" + }, + "description": "Sample for AddCollectionItem", + "file": "visionai_v1_generated_warehouse_add_collection_item_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_AddCollectionItem_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_add_collection_item_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.analyze_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.AnalyzeAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "AnalyzeAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AnalyzeAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "analyze_asset" + }, + "description": "Sample for AnalyzeAsset", + "file": "visionai_v1_generated_warehouse_analyze_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_AnalyzeAsset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_analyze_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.analyze_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.AnalyzeAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "AnalyzeAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AnalyzeAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "analyze_asset" + }, + "description": "Sample for AnalyzeAsset", + "file": "visionai_v1_generated_warehouse_analyze_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_AnalyzeAsset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_analyze_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.analyze_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.AnalyzeCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "AnalyzeCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AnalyzeCorpusRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "analyze_corpus" + }, + "description": "Sample for AnalyzeCorpus", + "file": "visionai_v1_generated_warehouse_analyze_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_AnalyzeCorpus_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_analyze_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.analyze_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.AnalyzeCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "AnalyzeCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.AnalyzeCorpusRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "analyze_corpus" + }, + "description": "Sample for AnalyzeCorpus", + "file": "visionai_v1_generated_warehouse_analyze_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_AnalyzeCorpus_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_analyze_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.clip_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ClipAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ClipAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ClipAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ClipAssetResponse", + "shortName": "clip_asset" + }, + "description": "Sample for ClipAsset", + "file": "visionai_v1_generated_warehouse_clip_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ClipAsset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_clip_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.clip_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ClipAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ClipAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ClipAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.ClipAssetResponse", + "shortName": "clip_asset" + }, + "description": "Sample for ClipAsset", + "file": "visionai_v1_generated_warehouse_clip_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ClipAsset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_clip_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateAnnotationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1.types.Annotation" + }, + { + "name": "annotation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Annotation", + "shortName": "create_annotation" + }, + "description": "Sample for CreateAnnotation", + "file": "visionai_v1_generated_warehouse_create_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateAnnotation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateAnnotationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1.types.Annotation" + }, + { + "name": "annotation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Annotation", + "shortName": "create_annotation" + }, + "description": "Sample for CreateAnnotation", + "file": "visionai_v1_generated_warehouse_create_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateAnnotation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateAssetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1.types.Asset" + }, + { + "name": "asset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Asset", + "shortName": "create_asset" + }, + "description": "Sample for CreateAsset", + "file": "visionai_v1_generated_warehouse_create_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateAsset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateAssetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1.types.Asset" + }, + { + "name": "asset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Asset", + "shortName": "create_asset" + }, + "description": "Sample for CreateAsset", + "file": "visionai_v1_generated_warehouse_create_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateAsset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateCollectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "collection", + "type": "google.cloud.visionai_v1.types.Collection" + }, + { + "name": "collection_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_collection" + }, + "description": "Sample for CreateCollection", + "file": "visionai_v1_generated_warehouse_create_collection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateCollection_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_collection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateCollectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "collection", + "type": "google.cloud.visionai_v1.types.Collection" + }, + { + "name": "collection_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_collection" + }, + "description": "Sample for CreateCollection", + "file": "visionai_v1_generated_warehouse_create_collection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateCollection_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_collection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateCorpusRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1.types.Corpus" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_corpus" + }, + "description": "Sample for CreateCorpus", + "file": "visionai_v1_generated_warehouse_create_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateCorpus_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateCorpusRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1.types.Corpus" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_corpus" + }, + "description": "Sample for CreateCorpus", + "file": "visionai_v1_generated_warehouse_create_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateCorpus_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateDataSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1.types.DataSchema" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.DataSchema", + "shortName": "create_data_schema" + }, + "description": "Sample for CreateDataSchema", + "file": "visionai_v1_generated_warehouse_create_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateDataSchema_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateDataSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1.types.DataSchema" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.DataSchema", + "shortName": "create_data_schema" + }, + "description": "Sample for CreateDataSchema", + "file": "visionai_v1_generated_warehouse_create_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateDataSchema_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateIndexEndpointRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "index_endpoint", + "type": "google.cloud.visionai_v1.types.IndexEndpoint" + }, + { + "name": "index_endpoint_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_index_endpoint" + }, + "description": "Sample for CreateIndexEndpoint", + "file": "visionai_v1_generated_warehouse_create_index_endpoint_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateIndexEndpoint_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_index_endpoint_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateIndexEndpointRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "index_endpoint", + "type": "google.cloud.visionai_v1.types.IndexEndpoint" + }, + { + "name": "index_endpoint_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_index_endpoint" + }, + "description": "Sample for CreateIndexEndpoint", + "file": "visionai_v1_generated_warehouse_create_index_endpoint_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateIndexEndpoint_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_index_endpoint_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateIndexRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "index", + "type": "google.cloud.visionai_v1.types.Index" + }, + { + "name": "index_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_index" + }, + "description": "Sample for CreateIndex", + "file": "visionai_v1_generated_warehouse_create_index_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateIndex_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_index_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateIndexRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "index", + "type": "google.cloud.visionai_v1.types.Index" + }, + { + "name": "index_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_index" + }, + "description": "Sample for CreateIndex", + "file": "visionai_v1_generated_warehouse_create_index_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateIndex_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_index_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateSearchConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1.types.SearchConfig" + }, + { + "name": "search_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchConfig", + "shortName": "create_search_config" + }, + "description": "Sample for CreateSearchConfig", + "file": "visionai_v1_generated_warehouse_create_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateSearchConfig_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateSearchConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1.types.SearchConfig" + }, + { + "name": "search_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchConfig", + "shortName": "create_search_config" + }, + "description": "Sample for CreateSearchConfig", + "file": "visionai_v1_generated_warehouse_create_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateSearchConfig_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_search_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.create_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateSearchHypernymRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "search_hypernym", + "type": "google.cloud.visionai_v1.types.SearchHypernym" + }, + { + "name": "search_hypernym_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchHypernym", + "shortName": "create_search_hypernym" + }, + "description": "Sample for CreateSearchHypernym", + "file": "visionai_v1_generated_warehouse_create_search_hypernym_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateSearchHypernym_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_search_hypernym_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.create_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.CreateSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.CreateSearchHypernymRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "search_hypernym", + "type": "google.cloud.visionai_v1.types.SearchHypernym" + }, + { + "name": "search_hypernym_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchHypernym", + "shortName": "create_search_hypernym" + }, + "description": "Sample for CreateSearchHypernym", + "file": "visionai_v1_generated_warehouse_create_search_hypernym_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_CreateSearchHypernym_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_create_search_hypernym_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_annotation" + }, + "description": "Sample for DeleteAnnotation", + "file": "visionai_v1_generated_warehouse_delete_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteAnnotation_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_annotation" + }, + "description": "Sample for DeleteAnnotation", + "file": "visionai_v1_generated_warehouse_delete_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteAnnotation_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_asset" + }, + "description": "Sample for DeleteAsset", + "file": "visionai_v1_generated_warehouse_delete_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteAsset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_asset" + }, + "description": "Sample for DeleteAsset", + "file": "visionai_v1_generated_warehouse_delete_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteAsset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteCollectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_collection" + }, + "description": "Sample for DeleteCollection", + "file": "visionai_v1_generated_warehouse_delete_collection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteCollection_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_collection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteCollectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_collection" + }, + "description": "Sample for DeleteCollection", + "file": "visionai_v1_generated_warehouse_delete_collection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteCollection_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_collection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_corpus" + }, + "description": "Sample for DeleteCorpus", + "file": "visionai_v1_generated_warehouse_delete_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteCorpus_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_corpus" + }, + "description": "Sample for DeleteCorpus", + "file": "visionai_v1_generated_warehouse_delete_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteCorpus_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_data_schema" + }, + "description": "Sample for DeleteDataSchema", + "file": "visionai_v1_generated_warehouse_delete_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteDataSchema_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_data_schema" + }, + "description": "Sample for DeleteDataSchema", + "file": "visionai_v1_generated_warehouse_delete_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteDataSchema_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteIndexEndpointRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_index_endpoint" + }, + "description": "Sample for DeleteIndexEndpoint", + "file": "visionai_v1_generated_warehouse_delete_index_endpoint_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteIndexEndpoint_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_index_endpoint_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteIndexEndpointRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_index_endpoint" + }, + "description": "Sample for DeleteIndexEndpoint", + "file": "visionai_v1_generated_warehouse_delete_index_endpoint_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteIndexEndpoint_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_index_endpoint_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteIndexRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_index" + }, + "description": "Sample for DeleteIndex", + "file": "visionai_v1_generated_warehouse_delete_index_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteIndex_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_index_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteIndexRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_index" + }, + "description": "Sample for DeleteIndex", + "file": "visionai_v1_generated_warehouse_delete_index_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteIndex_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_index_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_search_config" + }, + "description": "Sample for DeleteSearchConfig", + "file": "visionai_v1_generated_warehouse_delete_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteSearchConfig_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_search_config" + }, + "description": "Sample for DeleteSearchConfig", + "file": "visionai_v1_generated_warehouse_delete_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteSearchConfig_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_search_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.delete_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteSearchHypernymRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_search_hypernym" + }, + "description": "Sample for DeleteSearchHypernym", + "file": "visionai_v1_generated_warehouse_delete_search_hypernym_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteSearchHypernym_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_search_hypernym_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.delete_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeleteSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeleteSearchHypernymRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_search_hypernym" + }, + "description": "Sample for DeleteSearchHypernym", + "file": "visionai_v1_generated_warehouse_delete_search_hypernym_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeleteSearchHypernym_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_delete_search_hypernym_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.deploy_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeployIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeployIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeployIndexRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "deploy_index" + }, + "description": "Sample for DeployIndex", + "file": "visionai_v1_generated_warehouse_deploy_index_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeployIndex_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_deploy_index_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.deploy_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.DeployIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeployIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.DeployIndexRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "deploy_index" + }, + "description": "Sample for DeployIndex", + "file": "visionai_v1_generated_warehouse_deploy_index_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_DeployIndex_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_deploy_index_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.generate_hls_uri", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GenerateHlsUri", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GenerateHlsUri" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GenerateHlsUriRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.GenerateHlsUriResponse", + "shortName": "generate_hls_uri" + }, + "description": "Sample for GenerateHlsUri", + "file": "visionai_v1_generated_warehouse_generate_hls_uri_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GenerateHlsUri_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_generate_hls_uri_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.generate_hls_uri", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GenerateHlsUri", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GenerateHlsUri" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GenerateHlsUriRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.GenerateHlsUriResponse", + "shortName": "generate_hls_uri" + }, + "description": "Sample for GenerateHlsUri", + "file": "visionai_v1_generated_warehouse_generate_hls_uri_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GenerateHlsUri_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_generate_hls_uri_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.generate_retrieval_url", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GenerateRetrievalUrl", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GenerateRetrievalUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GenerateRetrievalUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.GenerateRetrievalUrlResponse", + "shortName": "generate_retrieval_url" + }, + "description": "Sample for GenerateRetrievalUrl", + "file": "visionai_v1_generated_warehouse_generate_retrieval_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GenerateRetrievalUrl_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_generate_retrieval_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.generate_retrieval_url", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GenerateRetrievalUrl", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GenerateRetrievalUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GenerateRetrievalUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.GenerateRetrievalUrlResponse", + "shortName": "generate_retrieval_url" + }, + "description": "Sample for GenerateRetrievalUrl", + "file": "visionai_v1_generated_warehouse_generate_retrieval_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GenerateRetrievalUrl_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_generate_retrieval_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Annotation", + "shortName": "get_annotation" + }, + "description": "Sample for GetAnnotation", + "file": "visionai_v1_generated_warehouse_get_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetAnnotation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Annotation", + "shortName": "get_annotation" + }, + "description": "Sample for GetAnnotation", + "file": "visionai_v1_generated_warehouse_get_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetAnnotation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Asset", + "shortName": "get_asset" + }, + "description": "Sample for GetAsset", + "file": "visionai_v1_generated_warehouse_get_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetAsset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Asset", + "shortName": "get_asset" + }, + "description": "Sample for GetAsset", + "file": "visionai_v1_generated_warehouse_get_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetAsset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetCollectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Collection", + "shortName": "get_collection" + }, + "description": "Sample for GetCollection", + "file": "visionai_v1_generated_warehouse_get_collection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetCollection_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_collection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetCollectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Collection", + "shortName": "get_collection" + }, + "description": "Sample for GetCollection", + "file": "visionai_v1_generated_warehouse_get_collection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetCollection_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_collection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Corpus", + "shortName": "get_corpus" + }, + "description": "Sample for GetCorpus", + "file": "visionai_v1_generated_warehouse_get_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetCorpus_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Corpus", + "shortName": "get_corpus" + }, + "description": "Sample for GetCorpus", + "file": "visionai_v1_generated_warehouse_get_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetCorpus_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.DataSchema", + "shortName": "get_data_schema" + }, + "description": "Sample for GetDataSchema", + "file": "visionai_v1_generated_warehouse_get_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetDataSchema_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.DataSchema", + "shortName": "get_data_schema" + }, + "description": "Sample for GetDataSchema", + "file": "visionai_v1_generated_warehouse_get_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetDataSchema_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetIndexEndpointRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.IndexEndpoint", + "shortName": "get_index_endpoint" + }, + "description": "Sample for GetIndexEndpoint", + "file": "visionai_v1_generated_warehouse_get_index_endpoint_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetIndexEndpoint_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_index_endpoint_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetIndexEndpointRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.IndexEndpoint", + "shortName": "get_index_endpoint" + }, + "description": "Sample for GetIndexEndpoint", + "file": "visionai_v1_generated_warehouse_get_index_endpoint_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetIndexEndpoint_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_index_endpoint_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetIndexRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Index", + "shortName": "get_index" + }, + "description": "Sample for GetIndex", + "file": "visionai_v1_generated_warehouse_get_index_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetIndex_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_index_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetIndexRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Index", + "shortName": "get_index" + }, + "description": "Sample for GetIndex", + "file": "visionai_v1_generated_warehouse_get_index_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetIndex_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_index_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchConfig", + "shortName": "get_search_config" + }, + "description": "Sample for GetSearchConfig", + "file": "visionai_v1_generated_warehouse_get_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetSearchConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchConfig", + "shortName": "get_search_config" + }, + "description": "Sample for GetSearchConfig", + "file": "visionai_v1_generated_warehouse_get_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetSearchConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_search_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.get_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetSearchHypernymRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchHypernym", + "shortName": "get_search_hypernym" + }, + "description": "Sample for GetSearchHypernym", + "file": "visionai_v1_generated_warehouse_get_search_hypernym_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetSearchHypernym_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_search_hypernym_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.get_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.GetSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.GetSearchHypernymRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchHypernym", + "shortName": "get_search_hypernym" + }, + "description": "Sample for GetSearchHypernym", + "file": "visionai_v1_generated_warehouse_get_search_hypernym_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_GetSearchHypernym_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_get_search_hypernym_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.import_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ImportAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ImportAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ImportAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_assets" + }, + "description": "Sample for ImportAssets", + "file": "visionai_v1_generated_warehouse_import_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ImportAssets_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_import_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.import_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ImportAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ImportAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ImportAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_assets" + }, + "description": "Sample for ImportAssets", + "file": "visionai_v1_generated_warehouse_import_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ImportAssets_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_import_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.index_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.IndexAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "IndexAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.IndexAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "index_asset" + }, + "description": "Sample for IndexAsset", + "file": "visionai_v1_generated_warehouse_index_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_IndexAsset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_index_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.index_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.IndexAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "IndexAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.IndexAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "index_asset" + }, + "description": "Sample for IndexAsset", + "file": "visionai_v1_generated_warehouse_index_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_IndexAsset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_index_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.ingest_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.IngestAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "IngestAsset" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.IngestAssetRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.IngestAssetResponse]", + "shortName": "ingest_asset" + }, + "description": "Sample for IngestAsset", + "file": "visionai_v1_generated_warehouse_ingest_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_IngestAsset_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_ingest_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.ingest_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.IngestAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "IngestAsset" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1.types.IngestAssetRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1.types.IngestAssetResponse]", + "shortName": "ingest_asset" + }, + "description": "Sample for IngestAsset", + "file": "visionai_v1_generated_warehouse_ingest_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_IngestAsset_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_ingest_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_annotations", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListAnnotations", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAnnotations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListAnnotationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListAnnotationsAsyncPager", + "shortName": "list_annotations" + }, + "description": "Sample for ListAnnotations", + "file": "visionai_v1_generated_warehouse_list_annotations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListAnnotations_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_annotations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_annotations", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListAnnotations", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAnnotations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListAnnotationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListAnnotationsPager", + "shortName": "list_annotations" + }, + "description": "Sample for ListAnnotations", + "file": "visionai_v1_generated_warehouse_list_annotations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListAnnotations_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_annotations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListAssetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "visionai_v1_generated_warehouse_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListAssets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListAssetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "visionai_v1_generated_warehouse_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListAssets_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_collections", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListCollections", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListCollections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListCollectionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListCollectionsAsyncPager", + "shortName": "list_collections" + }, + "description": "Sample for ListCollections", + "file": "visionai_v1_generated_warehouse_list_collections_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListCollections_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_collections_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_collections", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListCollections", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListCollections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListCollectionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListCollectionsPager", + "shortName": "list_collections" + }, + "description": "Sample for ListCollections", + "file": "visionai_v1_generated_warehouse_list_collections_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListCollections_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_collections_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_corpora", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListCorpora", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListCorpora" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListCorporaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListCorporaAsyncPager", + "shortName": "list_corpora" + }, + "description": "Sample for ListCorpora", + "file": "visionai_v1_generated_warehouse_list_corpora_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListCorpora_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_corpora_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_corpora", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListCorpora", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListCorpora" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListCorporaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListCorporaPager", + "shortName": "list_corpora" + }, + "description": "Sample for ListCorpora", + "file": "visionai_v1_generated_warehouse_list_corpora_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListCorpora_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_corpora_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_data_schemas", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListDataSchemas", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListDataSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListDataSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListDataSchemasAsyncPager", + "shortName": "list_data_schemas" + }, + "description": "Sample for ListDataSchemas", + "file": "visionai_v1_generated_warehouse_list_data_schemas_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListDataSchemas_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_data_schemas_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_data_schemas", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListDataSchemas", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListDataSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListDataSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListDataSchemasPager", + "shortName": "list_data_schemas" + }, + "description": "Sample for ListDataSchemas", + "file": "visionai_v1_generated_warehouse_list_data_schemas_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListDataSchemas_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_data_schemas_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_index_endpoints", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListIndexEndpoints", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListIndexEndpoints" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListIndexEndpointsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListIndexEndpointsAsyncPager", + "shortName": "list_index_endpoints" + }, + "description": "Sample for ListIndexEndpoints", + "file": "visionai_v1_generated_warehouse_list_index_endpoints_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListIndexEndpoints_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_index_endpoints_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_index_endpoints", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListIndexEndpoints", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListIndexEndpoints" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListIndexEndpointsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListIndexEndpointsPager", + "shortName": "list_index_endpoints" + }, + "description": "Sample for ListIndexEndpoints", + "file": "visionai_v1_generated_warehouse_list_index_endpoints_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListIndexEndpoints_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_index_endpoints_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_indexes", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListIndexes", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListIndexes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListIndexesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListIndexesAsyncPager", + "shortName": "list_indexes" + }, + "description": "Sample for ListIndexes", + "file": "visionai_v1_generated_warehouse_list_indexes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListIndexes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_indexes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_indexes", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListIndexes", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListIndexes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListIndexesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListIndexesPager", + "shortName": "list_indexes" + }, + "description": "Sample for ListIndexes", + "file": "visionai_v1_generated_warehouse_list_indexes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListIndexes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_indexes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_search_configs", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListSearchConfigs", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListSearchConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListSearchConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListSearchConfigsAsyncPager", + "shortName": "list_search_configs" + }, + "description": "Sample for ListSearchConfigs", + "file": "visionai_v1_generated_warehouse_list_search_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListSearchConfigs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_search_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_search_configs", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListSearchConfigs", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListSearchConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListSearchConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListSearchConfigsPager", + "shortName": "list_search_configs" + }, + "description": "Sample for ListSearchConfigs", + "file": "visionai_v1_generated_warehouse_list_search_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListSearchConfigs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_search_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.list_search_hypernyms", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListSearchHypernyms", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListSearchHypernyms" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListSearchHypernymsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListSearchHypernymsAsyncPager", + "shortName": "list_search_hypernyms" + }, + "description": "Sample for ListSearchHypernyms", + "file": "visionai_v1_generated_warehouse_list_search_hypernyms_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListSearchHypernyms_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_search_hypernyms_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.list_search_hypernyms", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ListSearchHypernyms", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListSearchHypernyms" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ListSearchHypernymsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ListSearchHypernymsPager", + "shortName": "list_search_hypernyms" + }, + "description": "Sample for ListSearchHypernyms", + "file": "visionai_v1_generated_warehouse_list_search_hypernyms_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ListSearchHypernyms_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_list_search_hypernyms_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.remove_collection_item", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.RemoveCollectionItem", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "RemoveCollectionItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RemoveCollectionItemRequest" + }, + { + "name": "item", + "type": "google.cloud.visionai_v1.types.CollectionItem" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.RemoveCollectionItemResponse", + "shortName": "remove_collection_item" + }, + "description": "Sample for RemoveCollectionItem", + "file": "visionai_v1_generated_warehouse_remove_collection_item_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_RemoveCollectionItem_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_remove_collection_item_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.remove_collection_item", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.RemoveCollectionItem", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "RemoveCollectionItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RemoveCollectionItemRequest" + }, + { + "name": "item", + "type": "google.cloud.visionai_v1.types.CollectionItem" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.RemoveCollectionItemResponse", + "shortName": "remove_collection_item" + }, + "description": "Sample for RemoveCollectionItem", + "file": "visionai_v1_generated_warehouse_remove_collection_item_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_RemoveCollectionItem_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_remove_collection_item_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.remove_index_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.RemoveIndexAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "RemoveIndexAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RemoveIndexAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "remove_index_asset" + }, + "description": "Sample for RemoveIndexAsset", + "file": "visionai_v1_generated_warehouse_remove_index_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_RemoveIndexAsset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_remove_index_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.remove_index_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.RemoveIndexAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "RemoveIndexAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.RemoveIndexAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "remove_index_asset" + }, + "description": "Sample for RemoveIndexAsset", + "file": "visionai_v1_generated_warehouse_remove_index_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_RemoveIndexAsset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_remove_index_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.search_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.SearchAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "SearchAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.SearchAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.SearchAssetsAsyncPager", + "shortName": "search_assets" + }, + "description": "Sample for SearchAssets", + "file": "visionai_v1_generated_warehouse_search_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_SearchAssets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_search_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.search_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.SearchAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "SearchAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.SearchAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.SearchAssetsPager", + "shortName": "search_assets" + }, + "description": "Sample for SearchAssets", + "file": "visionai_v1_generated_warehouse_search_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_SearchAssets_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_search_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.search_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.SearchIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "SearchIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.SearchIndexEndpointRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.SearchIndexEndpointAsyncPager", + "shortName": "search_index_endpoint" + }, + "description": "Sample for SearchIndexEndpoint", + "file": "visionai_v1_generated_warehouse_search_index_endpoint_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_SearchIndexEndpoint_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_search_index_endpoint_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.search_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.SearchIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "SearchIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.SearchIndexEndpointRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.SearchIndexEndpointPager", + "shortName": "search_index_endpoint" + }, + "description": "Sample for SearchIndexEndpoint", + "file": "visionai_v1_generated_warehouse_search_index_endpoint_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_SearchIndexEndpoint_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_search_index_endpoint_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.undeploy_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UndeployIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UndeployIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UndeployIndexRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "undeploy_index" + }, + "description": "Sample for UndeployIndex", + "file": "visionai_v1_generated_warehouse_undeploy_index_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UndeployIndex_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_undeploy_index_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.undeploy_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UndeployIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UndeployIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UndeployIndexRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "undeploy_index" + }, + "description": "Sample for UndeployIndex", + "file": "visionai_v1_generated_warehouse_undeploy_index_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UndeployIndex_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_undeploy_index_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateAnnotationRequest" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1.types.Annotation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Annotation", + "shortName": "update_annotation" + }, + "description": "Sample for UpdateAnnotation", + "file": "visionai_v1_generated_warehouse_update_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateAnnotation_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_annotation", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateAnnotationRequest" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1.types.Annotation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Annotation", + "shortName": "update_annotation" + }, + "description": "Sample for UpdateAnnotation", + "file": "visionai_v1_generated_warehouse_update_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateAnnotation_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateAssetRequest" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1.types.Asset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Asset", + "shortName": "update_asset" + }, + "description": "Sample for UpdateAsset", + "file": "visionai_v1_generated_warehouse_update_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateAsset_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateAssetRequest" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1.types.Asset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Asset", + "shortName": "update_asset" + }, + "description": "Sample for UpdateAsset", + "file": "visionai_v1_generated_warehouse_update_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateAsset_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateCollectionRequest" + }, + { + "name": "collection", + "type": "google.cloud.visionai_v1.types.Collection" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Collection", + "shortName": "update_collection" + }, + "description": "Sample for UpdateCollection", + "file": "visionai_v1_generated_warehouse_update_collection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateCollection_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_collection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_collection", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateCollection", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateCollectionRequest" + }, + { + "name": "collection", + "type": "google.cloud.visionai_v1.types.Collection" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Collection", + "shortName": "update_collection" + }, + "description": "Sample for UpdateCollection", + "file": "visionai_v1_generated_warehouse_update_collection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateCollection_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_collection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateCorpusRequest" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1.types.Corpus" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Corpus", + "shortName": "update_corpus" + }, + "description": "Sample for UpdateCorpus", + "file": "visionai_v1_generated_warehouse_update_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateCorpus_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_corpus", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateCorpusRequest" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1.types.Corpus" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.Corpus", + "shortName": "update_corpus" + }, + "description": "Sample for UpdateCorpus", + "file": "visionai_v1_generated_warehouse_update_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateCorpus_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateDataSchemaRequest" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1.types.DataSchema" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.DataSchema", + "shortName": "update_data_schema" + }, + "description": "Sample for UpdateDataSchema", + "file": "visionai_v1_generated_warehouse_update_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateDataSchema_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateDataSchemaRequest" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1.types.DataSchema" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.DataSchema", + "shortName": "update_data_schema" + }, + "description": "Sample for UpdateDataSchema", + "file": "visionai_v1_generated_warehouse_update_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateDataSchema_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateIndexEndpointRequest" + }, + { + "name": "index_endpoint", + "type": "google.cloud.visionai_v1.types.IndexEndpoint" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_index_endpoint" + }, + "description": "Sample for UpdateIndexEndpoint", + "file": "visionai_v1_generated_warehouse_update_index_endpoint_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateIndexEndpoint_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_index_endpoint_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_index_endpoint", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateIndexEndpoint", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateIndexEndpoint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateIndexEndpointRequest" + }, + { + "name": "index_endpoint", + "type": "google.cloud.visionai_v1.types.IndexEndpoint" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_index_endpoint" + }, + "description": "Sample for UpdateIndexEndpoint", + "file": "visionai_v1_generated_warehouse_update_index_endpoint_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateIndexEndpoint_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_index_endpoint_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateIndexRequest" + }, + { + "name": "index", + "type": "google.cloud.visionai_v1.types.Index" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_index" + }, + "description": "Sample for UpdateIndex", + "file": "visionai_v1_generated_warehouse_update_index_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateIndex_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_index_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_index", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateIndex", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateIndex" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateIndexRequest" + }, + { + "name": "index", + "type": "google.cloud.visionai_v1.types.Index" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_index" + }, + "description": "Sample for UpdateIndex", + "file": "visionai_v1_generated_warehouse_update_index_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateIndex_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_index_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateSearchConfigRequest" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1.types.SearchConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchConfig", + "shortName": "update_search_config" + }, + "description": "Sample for UpdateSearchConfig", + "file": "visionai_v1_generated_warehouse_update_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateSearchConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_search_config", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateSearchConfigRequest" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1.types.SearchConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchConfig", + "shortName": "update_search_config" + }, + "description": "Sample for UpdateSearchConfig", + "file": "visionai_v1_generated_warehouse_update_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateSearchConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_search_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.update_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateSearchHypernymRequest" + }, + { + "name": "search_hypernym", + "type": "google.cloud.visionai_v1.types.SearchHypernym" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchHypernym", + "shortName": "update_search_hypernym" + }, + "description": "Sample for UpdateSearchHypernym", + "file": "visionai_v1_generated_warehouse_update_search_hypernym_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateSearchHypernym_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_search_hypernym_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.update_search_hypernym", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UpdateSearchHypernym", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateSearchHypernym" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UpdateSearchHypernymRequest" + }, + { + "name": "search_hypernym", + "type": "google.cloud.visionai_v1.types.SearchHypernym" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.types.SearchHypernym", + "shortName": "update_search_hypernym" + }, + "description": "Sample for UpdateSearchHypernym", + "file": "visionai_v1_generated_warehouse_update_search_hypernym_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UpdateSearchHypernym_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_update_search_hypernym_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.upload_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UploadAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UploadAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UploadAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "upload_asset" + }, + "description": "Sample for UploadAsset", + "file": "visionai_v1_generated_warehouse_upload_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UploadAsset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_upload_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.upload_asset", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.UploadAsset", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UploadAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.UploadAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "upload_asset" + }, + "description": "Sample for UploadAsset", + "file": "visionai_v1_generated_warehouse_upload_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_UploadAsset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_upload_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.view_collection_items", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ViewCollectionItems", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ViewCollectionItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ViewCollectionItemsRequest" + }, + { + "name": "collection", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ViewCollectionItemsAsyncPager", + "shortName": "view_collection_items" + }, + "description": "Sample for ViewCollectionItems", + "file": "visionai_v1_generated_warehouse_view_collection_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ViewCollectionItems_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_view_collection_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.view_collection_items", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ViewCollectionItems", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ViewCollectionItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ViewCollectionItemsRequest" + }, + { + "name": "collection", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ViewCollectionItemsPager", + "shortName": "view_collection_items" + }, + "description": "Sample for ViewCollectionItems", + "file": "visionai_v1_generated_warehouse_view_collection_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ViewCollectionItems_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_view_collection_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseAsyncClient.view_indexed_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ViewIndexedAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ViewIndexedAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ViewIndexedAssetsRequest" + }, + { + "name": "index", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ViewIndexedAssetsAsyncPager", + "shortName": "view_indexed_assets" + }, + "description": "Sample for ViewIndexedAssets", + "file": "visionai_v1_generated_warehouse_view_indexed_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ViewIndexedAssets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_view_indexed_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1.WarehouseClient.view_indexed_assets", + "method": { + "fullName": "google.cloud.visionai.v1.Warehouse.ViewIndexedAssets", + "service": { + "fullName": "google.cloud.visionai.v1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ViewIndexedAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1.types.ViewIndexedAssetsRequest" + }, + { + "name": "index", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1.services.warehouse.pagers.ViewIndexedAssetsPager", + "shortName": "view_indexed_assets" + }, + "description": "Sample for ViewIndexedAssets", + "file": "visionai_v1_generated_warehouse_view_indexed_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1_generated_Warehouse_ViewIndexedAssets_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1_generated_warehouse_view_indexed_assets_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_add_application_stream_input_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_add_application_stream_input_async.py new file mode 100644 index 000000000000..7468270540a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_add_application_stream_input_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_AddApplicationStreamInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_add_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_AddApplicationStreamInput_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_add_application_stream_input_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_add_application_stream_input_sync.py new file mode 100644 index 000000000000..110b5e4d6592 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_add_application_stream_input_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_AddApplicationStreamInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_add_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_AddApplicationStreamInput_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_async.py new file mode 100644 index 000000000000..2178b109f7b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_instances_async.py new file mode 100644 index 000000000000..1f21bc068b60 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_instances_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateApplicationInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_application_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application_instances = visionai_v1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateApplicationInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_instances_sync.py new file mode 100644 index 000000000000..e700647843ba --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_instances_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateApplicationInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_application_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + application_instances = visionai_v1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateApplicationInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_sync.py new file mode 100644 index 000000000000..eba9d35f3f6d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_application_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_draft_async.py new file mode 100644 index 000000000000..1e6d1adec55c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_draft_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_draft_sync.py new file mode 100644 index 000000000000..a317f9996d00 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_draft_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_processor_async.py new file mode 100644 index 000000000000..a7854251038a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_processor_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_processor_sync.py new file mode 100644 index 000000000000..7babc8bf9742 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_create_processor_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_CreateProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_CreateProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_async.py new file mode 100644 index 000000000000..52203b74c5ed --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_instances_async.py new file mode 100644 index 000000000000..c97beadb486a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_instances_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteApplicationInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_application_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteApplicationInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_instances_sync.py new file mode 100644 index 000000000000..bb84d4182ede --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_instances_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteApplicationInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_application_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteApplicationInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_sync.py new file mode 100644 index 000000000000..6e80d13c93b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_application_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_draft_async.py new file mode 100644 index 000000000000..8a28ea749384 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_draft_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_draft_sync.py new file mode 100644 index 000000000000..30331be57a52 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_draft_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_processor_async.py new file mode 100644 index 000000000000..eb99a1ae9983 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_processor_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_processor_sync.py new file mode 100644 index 000000000000..f1d39a9b462f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_delete_processor_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeleteProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeleteProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_deploy_application_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_deploy_application_async.py new file mode 100644 index 000000000000..8324df0ee63d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_deploy_application_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeployApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_deploy_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeployApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_deploy_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_deploy_application_sync.py new file mode 100644 index 000000000000..a5f3a31324ca --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_deploy_application_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_DeployApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_deploy_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_DeployApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_application_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_application_async.py new file mode 100644 index 000000000000..4f28629c84c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_application_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_application(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_application_sync.py new file mode 100644 index 000000000000..6d5482185fa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_application_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = client.get_application(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_draft_async.py new file mode 100644 index 000000000000..25811d6e1085 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_draft_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = await client.get_draft(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_draft_sync.py new file mode 100644 index 000000000000..f61a4822c50d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_draft_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = client.get_draft(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_instance_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_instance_async.py new file mode 100644 index 000000000000..0071ec0eaac5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_instance_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_instance(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetInstance_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_instance_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_instance_sync.py new file mode 100644 index 000000000000..6edd1c9b10d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_instance_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_instance(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetInstance_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_processor_async.py new file mode 100644 index 000000000000..f904ad0d9a1c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_processor_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_processor_sync.py new file mode 100644 index 000000000000..d9b3267dbf33 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_get_processor_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_GetProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_GetProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_applications_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_applications_async.py new file mode 100644 index 000000000000..f0e6d1cd526c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_applications_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListApplications +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListApplications_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_applications(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListApplications_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_applications_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_applications_sync.py new file mode 100644 index 000000000000..e41c87f6060c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_applications_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListApplications +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListApplications_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_applications(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListApplications_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_drafts_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_drafts_async.py new file mode 100644 index 000000000000..732355ee013d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_drafts_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDrafts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListDrafts_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_drafts(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListDrafts_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_drafts_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_drafts_sync.py new file mode 100644 index 000000000000..2273649bb36b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_drafts_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDrafts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListDrafts_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_drafts(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListDrafts_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_instances_async.py new file mode 100644 index 000000000000..0c15d0b02f4c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_instances_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_instances_sync.py new file mode 100644 index 000000000000..e023fa7b0ac5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_instances_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_prebuilt_processors_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_prebuilt_processors_async.py new file mode 100644 index 000000000000..eaf6c53ec796 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_prebuilt_processors_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPrebuiltProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListPrebuiltProcessors_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_ListPrebuiltProcessors_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_prebuilt_processors_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_prebuilt_processors_sync.py new file mode 100644 index 000000000000..b28524b40c39 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_prebuilt_processors_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPrebuiltProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListPrebuiltProcessors_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_ListPrebuiltProcessors_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_processors_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_processors_async.py new file mode 100644 index 000000000000..c495f935a9a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_processors_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListProcessors_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_processors(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListProcessors_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_processors_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_processors_sync.py new file mode 100644 index 000000000000..bd2babbfc991 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_list_processors_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_ListProcessors_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_processors(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_AppPlatform_ListProcessors_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_remove_application_stream_input_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_remove_application_stream_input_async.py new file mode 100644 index 000000000000..2e89ef26faed --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_remove_application_stream_input_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_RemoveApplicationStreamInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_RemoveApplicationStreamInput_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_remove_application_stream_input_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_remove_application_stream_input_sync.py new file mode 100644 index 000000000000..79909c71406a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_remove_application_stream_input_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_RemoveApplicationStreamInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_RemoveApplicationStreamInput_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_undeploy_application_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_undeploy_application_async.py new file mode 100644 index 000000000000..78e1e96413a1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_undeploy_application_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UndeployApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_undeploy_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UndeployApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_undeploy_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_undeploy_application_sync.py new file mode 100644 index 000000000000..c2001cea5467 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_undeploy_application_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UndeployApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_undeploy_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UndeployApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_async.py new file mode 100644 index 000000000000..2597c52275fb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_application(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_instances_async.py new file mode 100644 index 000000000000..910ce8adaae4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_instances_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateApplicationInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_application_instances(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateApplicationInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_instances_sync.py new file mode 100644 index 000000000000..676017cc317e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_instances_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateApplicationInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_application_instances(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateApplicationInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_stream_input_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_stream_input_async.py new file mode 100644 index 000000000000..df85fceed316 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_stream_input_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateApplicationStreamInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateApplicationStreamInput_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_stream_input_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_stream_input_sync.py new file mode 100644 index 000000000000..29ce18f46c26 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_stream_input_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateApplicationStreamInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_application_stream_input(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateApplicationStreamInput_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_sync.py new file mode 100644 index 000000000000..df3cb9320758 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_application_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_application(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1.Application() + application.display_name = "display_name_value" + + request = visionai_v1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_draft_async.py new file mode 100644 index 000000000000..e6761db12e16 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_draft_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_draft(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_draft_sync.py new file mode 100644 index 000000000000..a6fbf6aaa714 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_draft_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_draft(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_processor_async.py new file mode 100644 index 000000000000..2d2739409685 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_processor_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_processor(): + # Create a client + client = visionai_v1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_processor_sync.py new file mode 100644 index 000000000000..06ff6c204ab8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_app_platform_update_processor_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_AppPlatform_UpdateProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_processor(): + # Create a client + client = visionai_v1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_AppPlatform_UpdateProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_health_check_service_health_check_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_health_check_service_health_check_async.py new file mode 100644 index 000000000000..122d70b9d724 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_health_check_service_health_check_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for HealthCheck +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_HealthCheckService_HealthCheck_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_health_check(): + # Create a client + client = visionai_v1.HealthCheckServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.HealthCheckRequest( + ) + + # Make the request + response = await client.health_check(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_HealthCheckService_HealthCheck_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_health_check_service_health_check_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_health_check_service_health_check_sync.py new file mode 100644 index 000000000000..336cdd756e58 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_health_check_service_health_check_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for HealthCheck +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_HealthCheckService_HealthCheck_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_health_check(): + # Create a client + client = visionai_v1.HealthCheckServiceClient() + + # Initialize request argument(s) + request = visionai_v1.HealthCheckRequest( + ) + + # Make the request + response = client.health_check(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_HealthCheckService_HealthCheck_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_batch_run_process_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_batch_run_process_async.py new file mode 100644 index 000000000000..53742753afae --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_batch_run_process_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchRunProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_BatchRunProcess_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_batch_run_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + requests = visionai_v1.CreateProcessRequest() + requests.parent = "parent_value" + requests.process_id = "process_id_value" + requests.process.analysis = "analysis_value" + + request = visionai_v1.BatchRunProcessRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_run_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_BatchRunProcess_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_batch_run_process_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_batch_run_process_sync.py new file mode 100644 index 000000000000..9dbdb42d71dd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_batch_run_process_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchRunProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_BatchRunProcess_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_batch_run_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + requests = visionai_v1.CreateProcessRequest() + requests.parent = "parent_value" + requests.process_id = "process_id_value" + requests.process.analysis = "analysis_value" + + request = visionai_v1.BatchRunProcessRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_run_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_BatchRunProcess_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_analysis_async.py new file mode 100644 index 000000000000..605db3f3f90c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_analysis_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_CreateAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_CreateAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_analysis_sync.py new file mode 100644 index 000000000000..148ba178c5bd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_analysis_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_CreateAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_CreateAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_operator_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_operator_async.py new file mode 100644 index 000000000000..d5bc6c477ba8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_operator_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_CreateOperator_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateOperatorRequest( + parent="parent_value", + operator_id="operator_id_value", + ) + + # Make the request + operation = client.create_operator(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_CreateOperator_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_operator_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_operator_sync.py new file mode 100644 index 000000000000..8f2d678497d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_operator_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_CreateOperator_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.CreateOperatorRequest( + parent="parent_value", + operator_id="operator_id_value", + ) + + # Make the request + operation = client.create_operator(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_CreateOperator_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_process_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_process_async.py new file mode 100644 index 000000000000..e917fc9fc226 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_process_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_CreateProcess_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.CreateProcessRequest( + parent="parent_value", + process_id="process_id_value", + process=process, + ) + + # Make the request + operation = client.create_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_CreateProcess_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_process_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_process_sync.py new file mode 100644 index 000000000000..6e98dc22136d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_create_process_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_CreateProcess_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.CreateProcessRequest( + parent="parent_value", + process_id="process_id_value", + process=process, + ) + + # Make the request + operation = client.create_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_CreateProcess_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_analysis_async.py new file mode 100644 index 000000000000..8a6c761c41ba --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_analysis_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_DeleteAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_DeleteAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_analysis_sync.py new file mode 100644 index 000000000000..4f9c5cfaf379 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_analysis_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_DeleteAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_DeleteAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_operator_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_operator_async.py new file mode 100644 index 000000000000..e0b7979696f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_operator_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_DeleteOperator_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteOperatorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_operator(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_DeleteOperator_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_operator_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_operator_sync.py new file mode 100644 index 000000000000..b1e870ba6b93 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_operator_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_DeleteOperator_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteOperatorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_operator(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_DeleteOperator_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_process_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_process_async.py new file mode 100644 index 000000000000..46ba382cfd6e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_process_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_DeleteProcess_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_DeleteProcess_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_process_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_process_sync.py new file mode 100644 index 000000000000..17d5ecd25739 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_delete_process_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_DeleteProcess_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteProcessRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_DeleteProcess_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_analysis_async.py new file mode 100644 index 000000000000..dde1b4d26576 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_analysis_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_GetAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = await client.get_analysis(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_GetAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_analysis_sync.py new file mode 100644 index 000000000000..1dc7f30c2051 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_analysis_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_GetAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = client.get_analysis(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_GetAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_operator_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_operator_async.py new file mode 100644 index 000000000000..7b15ca243467 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_operator_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_GetOperator_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetOperatorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_operator(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_GetOperator_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_operator_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_operator_sync.py new file mode 100644 index 000000000000..e9c327a45d1b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_operator_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_GetOperator_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.GetOperatorRequest( + name="name_value", + ) + + # Make the request + response = client.get_operator(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_GetOperator_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_process_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_process_async.py new file mode 100644 index 000000000000..1204daaba864 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_process_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_GetProcess_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessRequest( + name="name_value", + ) + + # Make the request + response = await client.get_process(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_GetProcess_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_process_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_process_sync.py new file mode 100644 index 000000000000..819b270cf532 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_get_process_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_GetProcess_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.GetProcessRequest( + name="name_value", + ) + + # Make the request + response = client.get_process(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_GetProcess_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_analyses_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_analyses_async.py new file mode 100644 index 000000000000..4f02deb4d8bf --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_analyses_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnalyses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListAnalyses_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_analyses(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListAnalyses_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_analyses_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_analyses_sync.py new file mode 100644 index 000000000000..4e532745d4bd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_analyses_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnalyses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListAnalyses_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_analyses(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListAnalyses_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_operators_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_operators_async.py new file mode 100644 index 000000000000..3cb0bbb6a05d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_operators_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListOperators +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListOperators_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_operators(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListOperators_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_operators_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_operators_sync.py new file mode 100644 index 000000000000..8e722ffd8455 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_operators_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListOperators +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListOperators_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_operators(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListOperators_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_processes_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_processes_async.py new file mode 100644 index 000000000000..0153f4de4ed1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_processes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProcesses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListProcesses_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_processes(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListProcesses_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_processes_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_processes_sync.py new file mode 100644 index 000000000000..414e2620a8b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_processes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProcesses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListProcesses_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_processes(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListProcessesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListProcesses_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_public_operators_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_public_operators_async.py new file mode 100644 index 000000000000..98abd80de34a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_public_operators_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPublicOperators +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListPublicOperators_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_public_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListPublicOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_public_operators(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListPublicOperators_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_public_operators_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_public_operators_sync.py new file mode 100644 index 000000000000..423191ca45a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_list_public_operators_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPublicOperators +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ListPublicOperators_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_public_operators(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.ListPublicOperatorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_public_operators(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ListPublicOperators_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_resolve_operator_info_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_resolve_operator_info_async.py new file mode 100644 index 000000000000..39d6d35bfc54 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_resolve_operator_info_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ResolveOperatorInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ResolveOperatorInfo_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_resolve_operator_info(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + queries = visionai_v1.OperatorQuery() + queries.operator = "operator_value" + + request = visionai_v1.ResolveOperatorInfoRequest( + parent="parent_value", + queries=queries, + ) + + # Make the request + response = await client.resolve_operator_info(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ResolveOperatorInfo_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_resolve_operator_info_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_resolve_operator_info_sync.py new file mode 100644 index 000000000000..e1cccc780c25 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_resolve_operator_info_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ResolveOperatorInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_ResolveOperatorInfo_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_resolve_operator_info(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + queries = visionai_v1.OperatorQuery() + queries.operator = "operator_value" + + request = visionai_v1.ResolveOperatorInfoRequest( + parent="parent_value", + queries=queries, + ) + + # Make the request + response = client.resolve_operator_info(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_ResolveOperatorInfo_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_analysis_async.py new file mode 100644 index 000000000000..50acebd1b896 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_analysis_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_UpdateAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_UpdateAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_analysis_sync.py new file mode 100644 index 000000000000..394f9d83b98f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_analysis_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_UpdateAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_analysis(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_UpdateAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_operator_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_operator_async.py new file mode 100644 index 000000000000..f287695cf855 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_operator_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_UpdateOperator_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateOperatorRequest( + ) + + # Make the request + operation = client.update_operator(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_UpdateOperator_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_operator_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_operator_sync.py new file mode 100644 index 000000000000..2235104c76f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_operator_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateOperator +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_UpdateOperator_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_operator(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateOperatorRequest( + ) + + # Make the request + operation = client.update_operator(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_UpdateOperator_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_process_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_process_async.py new file mode 100644 index 000000000000..ab86420d522d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_process_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_UpdateProcess_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.UpdateProcessRequest( + process=process, + ) + + # Make the request + operation = client.update_process(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_UpdateProcess_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_process_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_process_sync.py new file mode 100644 index 000000000000..44cad8a39c31 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_live_video_analytics_update_process_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProcess +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_LiveVideoAnalytics_UpdateProcess_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_process(): + # Create a client + client = visionai_v1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + process = visionai_v1.Process() + process.analysis = "analysis_value" + + request = visionai_v1.UpdateProcessRequest( + process=process, + ) + + # Make the request + operation = client.update_process(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_LiveVideoAnalytics_UpdateProcess_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_acquire_lease_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_acquire_lease_async.py new file mode 100644 index 000000000000..b3079c9f9556 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_acquire_lease_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcquireLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_AcquireLease_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_acquire_lease(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AcquireLeaseRequest( + ) + + # Make the request + response = await client.acquire_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamingService_AcquireLease_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_acquire_lease_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_acquire_lease_sync.py new file mode 100644 index 000000000000..dff892f8c02f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_acquire_lease_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcquireLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_AcquireLease_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_acquire_lease(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.AcquireLeaseRequest( + ) + + # Make the request + response = client.acquire_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamingService_AcquireLease_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_events_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_events_async.py new file mode 100644 index 000000000000..cd437f017756 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_events_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceiveEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_ReceiveEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_receive_events(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_events(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1_generated_StreamingService_ReceiveEvents_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_events_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_events_sync.py new file mode 100644 index 000000000000..e18b64abaf73 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_events_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceiveEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_ReceiveEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_receive_events(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_events(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1_generated_StreamingService_ReceiveEvents_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_packets_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_packets_async.py new file mode 100644 index 000000000000..9982d6a13aca --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_packets_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceivePackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_ReceivePackets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_receive_packets(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1_generated_StreamingService_ReceivePackets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_packets_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_packets_sync.py new file mode 100644 index 000000000000..4512e3e82b62 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_receive_packets_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceivePackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_ReceivePackets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_receive_packets(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1_generated_StreamingService_ReceivePackets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_release_lease_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_release_lease_async.py new file mode 100644 index 000000000000..010b8684f946 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_release_lease_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReleaseLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_ReleaseLease_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_release_lease(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ReleaseLeaseRequest( + ) + + # Make the request + response = await client.release_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamingService_ReleaseLease_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_release_lease_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_release_lease_sync.py new file mode 100644 index 000000000000..887a68b732f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_release_lease_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReleaseLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_ReleaseLease_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_release_lease(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ReleaseLeaseRequest( + ) + + # Make the request + response = client.release_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamingService_ReleaseLease_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_renew_lease_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_renew_lease_async.py new file mode 100644 index 000000000000..f59fa0d68624 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_renew_lease_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RenewLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_RenewLease_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_renew_lease(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.RenewLeaseRequest( + ) + + # Make the request + response = await client.renew_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamingService_RenewLease_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_renew_lease_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_renew_lease_sync.py new file mode 100644 index 000000000000..81739e5ab4d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_renew_lease_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RenewLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_RenewLease_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_renew_lease(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.RenewLeaseRequest( + ) + + # Make the request + response = client.renew_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamingService_RenewLease_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_send_packets_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_send_packets_async.py new file mode 100644 index 000000000000..7c821b1fa2a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_send_packets_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendPackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_SendPackets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_send_packets(): + # Create a client + client = visionai_v1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.send_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1_generated_StreamingService_SendPackets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_send_packets_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_send_packets_sync.py new file mode 100644 index 000000000000..2842a6339029 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streaming_service_send_packets_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendPackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamingService_SendPackets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_send_packets(): + # Create a client + client = visionai_v1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.send_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1_generated_StreamingService_SendPackets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_cluster_async.py new file mode 100644 index 000000000000..2fe90e7ad5ab --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_cluster_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_cluster_sync.py new file mode 100644 index 000000000000..a8726074d44d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_cluster_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_event_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_event_async.py new file mode 100644 index 000000000000..46584dd5fde6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_event_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_event_sync.py new file mode 100644 index 000000000000..0aaf15edf703 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_event_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_series_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_series_async.py new file mode 100644 index 000000000000..5178a9345b43 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_series_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_series_sync.py new file mode 100644 index 000000000000..a64b5342a1f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_series_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_stream_async.py new file mode 100644 index 000000000000..b06b585fab26 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_stream_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_stream_sync.py new file mode 100644 index 000000000000..b1bf4593c3b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_create_stream_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_CreateStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_CreateStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_cluster_async.py new file mode 100644 index 000000000000..299cca2395a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_cluster_sync.py new file mode 100644 index 000000000000..6dcfcaa64fe8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_event_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_event_async.py new file mode 100644 index 000000000000..2c3b8936fa79 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_event_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_event_sync.py new file mode 100644 index 000000000000..d02d828e601c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_event_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_series_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_series_async.py new file mode 100644 index 000000000000..b5a3c26846de --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_series_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_series_sync.py new file mode 100644 index 000000000000..a3606064d10f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_series_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_stream_async.py new file mode 100644 index 000000000000..38975e2a5dba --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_stream_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_stream_sync.py new file mode 100644 index 000000000000..34dcd068fe82 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_delete_stream_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_DeleteStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_DeleteStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_generate_stream_hls_token_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_generate_stream_hls_token_async.py new file mode 100644 index 000000000000..70f082e3369a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_generate_stream_hls_token_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateStreamHlsToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GenerateStreamHlsToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = await client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GenerateStreamHlsToken_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_generate_stream_hls_token_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_generate_stream_hls_token_sync.py new file mode 100644 index 000000000000..ca45f5e32dcb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_generate_stream_hls_token_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateStreamHlsToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GenerateStreamHlsToken_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GenerateStreamHlsToken_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_cluster_async.py new file mode 100644 index 000000000000..196d2d47922f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_cluster_sync.py new file mode 100644 index 000000000000..44d7d8ee80ed --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_event_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_event_async.py new file mode 100644 index 000000000000..ca9330be73aa --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_event_sync.py new file mode 100644 index 000000000000..eea49f31b97c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_event(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_series_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_series_async.py new file mode 100644 index 000000000000..03766ce01750 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_series_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_series(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_series_sync.py new file mode 100644 index 000000000000..7a775bd30b30 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_series_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = client.get_series(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_async.py new file mode 100644 index 000000000000..8092d50082af --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = await client.get_stream(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_sync.py new file mode 100644 index 000000000000..88452679535d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = client.get_stream(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_thumbnail_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_thumbnail_async.py new file mode 100644 index 000000000000..e14baf04a777 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_thumbnail_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetStreamThumbnail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetStreamThumbnail_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_stream_thumbnail(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamThumbnailRequest( + stream="stream_value", + gcs_object_name="gcs_object_name_value", + ) + + # Make the request + operation = client.get_stream_thumbnail(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetStreamThumbnail_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_thumbnail_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_thumbnail_sync.py new file mode 100644 index 000000000000..b159bd1ceca4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_get_stream_thumbnail_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetStreamThumbnail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_GetStreamThumbnail_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_stream_thumbnail(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.GetStreamThumbnailRequest( + stream="stream_value", + gcs_object_name="gcs_object_name_value", + ) + + # Make the request + operation = client.get_stream_thumbnail(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_GetStreamThumbnail_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_clusters_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_clusters_async.py new file mode 100644 index 000000000000..f0ef9f41994f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListClusters_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_clusters(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListClusters_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_clusters_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_clusters_sync.py new file mode 100644 index 000000000000..17d7198ecacc --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListClusters_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_clusters(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListClusters_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_events_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_events_async.py new file mode 100644 index 000000000000..a60e113e3ef6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_events_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_events(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListEvents_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_events_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_events_sync.py new file mode 100644 index 000000000000..d2899bebac5e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_events_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_events(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListEvents_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_series_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_series_async.py new file mode 100644 index 000000000000..7dbb27e28ce9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_series_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_series_sync.py new file mode 100644 index 000000000000..45341b7461ea --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_series_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_streams_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_streams_async.py new file mode 100644 index 000000000000..7a874326d6aa --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_streams_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListStreams +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListStreams_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_streams(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListStreams_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_streams_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_streams_sync.py new file mode 100644 index 000000000000..fea0548713b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_list_streams_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListStreams +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_ListStreams_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_streams(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_StreamsService_ListStreams_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_materialize_channel_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_materialize_channel_async.py new file mode 100644 index 000000000000..1ceaf87c58e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_materialize_channel_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MaterializeChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_MaterializeChannel_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_materialize_channel(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + channel = visionai_v1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_MaterializeChannel_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_materialize_channel_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_materialize_channel_sync.py new file mode 100644 index 000000000000..0fabb7130678 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_materialize_channel_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MaterializeChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_MaterializeChannel_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_materialize_channel(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + channel = visionai_v1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_MaterializeChannel_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_cluster_async.py new file mode 100644 index 000000000000..3aec8e3913e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_cluster_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_cluster(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_cluster_sync.py new file mode 100644 index 000000000000..4d59ddc14374 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_cluster_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_cluster(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_event_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_event_async.py new file mode 100644 index 000000000000..e741d9a79fbb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_event_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_event(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_event_sync.py new file mode 100644 index 000000000000..075de39b308b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_event_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_event(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_series_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_series_async.py new file mode 100644 index 000000000000..ffbfaf9ac1d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_series_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_series(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_series_sync.py new file mode 100644 index 000000000000..0c6eb65f4a3c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_series_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_series(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_stream_async.py new file mode 100644 index 000000000000..e1ecfc2ddf53 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_stream_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_stream(): + # Create a client + client = visionai_v1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_stream_sync.py new file mode 100644 index 000000000000..56fb06fca06a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_streams_service_update_stream_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_StreamsService_UpdateStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_stream(): + # Create a client + client = visionai_v1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_StreamsService_UpdateStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_add_collection_item_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_add_collection_item_async.py new file mode 100644 index 000000000000..eb91095b37e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_add_collection_item_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCollectionItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_AddCollectionItem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_add_collection_item(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.AddCollectionItemRequest( + item=item, + ) + + # Make the request + response = await client.add_collection_item(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_AddCollectionItem_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_add_collection_item_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_add_collection_item_sync.py new file mode 100644 index 000000000000..7705e78cd2c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_add_collection_item_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddCollectionItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_AddCollectionItem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_add_collection_item(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.AddCollectionItemRequest( + item=item, + ) + + # Make the request + response = client.add_collection_item(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_AddCollectionItem_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_asset_async.py new file mode 100644 index 000000000000..d2718cfeb59f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_asset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_AnalyzeAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_analyze_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_AnalyzeAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_asset_sync.py new file mode 100644 index 000000000000..3bf87672cf7b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_asset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_AnalyzeAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_analyze_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_AnalyzeAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_corpus_async.py new file mode 100644 index 000000000000..a94820f39280 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_corpus_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_AnalyzeCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_analyze_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeCorpusRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_corpus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_AnalyzeCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_corpus_sync.py new file mode 100644 index 000000000000..ac8150bf5b70 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_analyze_corpus_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_AnalyzeCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_analyze_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.AnalyzeCorpusRequest( + name="name_value", + ) + + # Make the request + operation = client.analyze_corpus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_AnalyzeCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_clip_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_clip_asset_async.py new file mode 100644 index 000000000000..8bd0770b764c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_clip_asset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClipAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ClipAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_clip_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.clip_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_ClipAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_clip_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_clip_asset_sync.py new file mode 100644 index 000000000000..c3cbefc3dcd9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_clip_asset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClipAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ClipAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_clip_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = client.clip_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_ClipAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_annotation_async.py new file mode 100644 index 000000000000..5fa72e29979b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_annotation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_annotation_sync.py new file mode 100644 index 000000000000..c7e69e9ec077 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_annotation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_asset_async.py new file mode 100644 index 000000000000..790cf0c916ae --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_asset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_asset_sync.py new file mode 100644 index 000000000000..334123404b39 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_asset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_collection_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_collection_async.py new file mode 100644 index 000000000000..35390eed9c6b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_collection_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateCollection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateCollectionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_collection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateCollection_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_collection_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_collection_sync.py new file mode 100644 index 000000000000..ee70dd3579f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_collection_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateCollection_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateCollectionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_collection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateCollection_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_corpus_async.py new file mode 100644 index 000000000000..03d88a5b324a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_corpus_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_corpus_sync.py new file mode 100644 index 000000000000..6b0577743be9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_corpus_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_data_schema_async.py new file mode 100644 index 000000000000..e83242f0ae33 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_data_schema_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = await client.create_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_data_schema_sync.py new file mode 100644 index 000000000000..704ed2baae7e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_data_schema_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = client.create_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_async.py new file mode 100644 index 000000000000..fc1be88cd836 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateIndex_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.CreateIndexRequest( + parent="parent_value", + index=index, + ) + + # Make the request + operation = client.create_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateIndex_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_endpoint_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_endpoint_async.py new file mode 100644 index 000000000000..65e49d8c9852 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_endpoint_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateIndexEndpoint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateIndexEndpointRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateIndexEndpoint_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_endpoint_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_endpoint_sync.py new file mode 100644 index 000000000000..ebc56762fe4a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_endpoint_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateIndexEndpoint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateIndexEndpointRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateIndexEndpoint_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_sync.py new file mode 100644 index 000000000000..6240aa6c9c1d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_index_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateIndex_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.CreateIndexRequest( + parent="parent_value", + index=index, + ) + + # Make the request + operation = client.create_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateIndex_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_config_async.py new file mode 100644 index 000000000000..ffb942ea73d1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_config_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = await client.create_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_config_sync.py new file mode 100644 index 000000000000..437601b8adf9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_config_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = client.create_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_hypernym_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_hypernym_async.py new file mode 100644 index 000000000000..6bb6b5c8fb1e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_hypernym_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateSearchHypernym_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_create_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchHypernymRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_search_hypernym(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateSearchHypernym_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_hypernym_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_hypernym_sync.py new file mode 100644 index 000000000000..95c2a8529b74 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_create_search_hypernym_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_CreateSearchHypernym_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_create_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.CreateSearchHypernymRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_search_hypernym(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_CreateSearchHypernym_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_annotation_async.py new file mode 100644 index 000000000000..b5a98f721731 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_annotation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + await client.delete_annotation(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_annotation_sync.py new file mode 100644 index 000000000000..c6ba402f22a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_annotation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + client.delete_annotation(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_asset_async.py new file mode 100644 index 000000000000..1be540d3708c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_asset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_asset_sync.py new file mode 100644 index 000000000000..8112073f45dd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_asset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_collection_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_collection_async.py new file mode 100644 index 000000000000..9fe38601f662 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_collection_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteCollection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCollectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_collection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteCollection_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_collection_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_collection_sync.py new file mode 100644 index 000000000000..b1b5405c00f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_collection_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteCollection_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCollectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_collection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteCollection_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_corpus_async.py new file mode 100644 index 000000000000..84379a916a1d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_corpus_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + await client.delete_corpus(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_corpus_sync.py new file mode 100644 index 000000000000..71187de5f08f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_corpus_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + client.delete_corpus(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_data_schema_async.py new file mode 100644 index 000000000000..f912b2e7df3b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_data_schema_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_schema(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_data_schema_sync.py new file mode 100644 index 000000000000..59c0b116e5c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_data_schema_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + client.delete_data_schema(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_async.py new file mode 100644 index 000000000000..19f820eddf75 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteIndex_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteIndex_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_endpoint_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_endpoint_async.py new file mode 100644 index 000000000000..cd2e77df0d68 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_endpoint_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteIndexEndpoint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexEndpointRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteIndexEndpoint_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_endpoint_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_endpoint_sync.py new file mode 100644 index 000000000000..1fe97c7cb3ed --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_endpoint_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteIndexEndpoint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexEndpointRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteIndexEndpoint_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_sync.py new file mode 100644 index 000000000000..8640fc90141d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_index_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteIndex_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteIndexRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeleteIndex_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_config_async.py new file mode 100644 index 000000000000..c6528e0ca817 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_config_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_search_config(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_config_sync.py new file mode 100644 index 000000000000..0fd1008f909b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_config_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_search_config(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_hypernym_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_hypernym_async.py new file mode 100644 index 000000000000..1a754d5b04a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_hypernym_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteSearchHypernym_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_delete_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchHypernymRequest( + name="name_value", + ) + + # Make the request + await client.delete_search_hypernym(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteSearchHypernym_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_hypernym_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_hypernym_sync.py new file mode 100644 index 000000000000..3031c0940f7e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_delete_search_hypernym_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeleteSearchHypernym_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_delete_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.DeleteSearchHypernymRequest( + name="name_value", + ) + + # Make the request + client.delete_search_hypernym(request=request) + + +# [END visionai_v1_generated_Warehouse_DeleteSearchHypernym_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_deploy_index_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_deploy_index_async.py new file mode 100644 index 000000000000..e81b748d926e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_deploy_index_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeployIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeployIndex_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_deploy_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + deployed_index = visionai_v1.DeployedIndex() + deployed_index.index = "index_value" + + request = visionai_v1.DeployIndexRequest( + index_endpoint="index_endpoint_value", + deployed_index=deployed_index, + ) + + # Make the request + operation = client.deploy_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeployIndex_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_deploy_index_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_deploy_index_sync.py new file mode 100644 index 000000000000..891a8ee58d57 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_deploy_index_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeployIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_DeployIndex_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_deploy_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + deployed_index = visionai_v1.DeployedIndex() + deployed_index.index = "index_value" + + request = visionai_v1.DeployIndexRequest( + index_endpoint="index_endpoint_value", + deployed_index=deployed_index, + ) + + # Make the request + operation = client.deploy_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_DeployIndex_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_hls_uri_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_hls_uri_async.py new file mode 100644 index 000000000000..1f56d52b930c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_hls_uri_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateHlsUri +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GenerateHlsUri_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_generate_hls_uri(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_hls_uri(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GenerateHlsUri_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_hls_uri_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_hls_uri_sync.py new file mode 100644 index 000000000000..0ee2df077905 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_hls_uri_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateHlsUri +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GenerateHlsUri_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_generate_hls_uri(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = client.generate_hls_uri(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GenerateHlsUri_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_retrieval_url_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_retrieval_url_async.py new file mode 100644 index 000000000000..b90b790d740b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_retrieval_url_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateRetrievalUrl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GenerateRetrievalUrl_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_generate_retrieval_url(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateRetrievalUrlRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_retrieval_url(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GenerateRetrievalUrl_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_retrieval_url_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_retrieval_url_sync.py new file mode 100644 index 000000000000..55f851d74858 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_generate_retrieval_url_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateRetrievalUrl +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GenerateRetrievalUrl_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_generate_retrieval_url(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GenerateRetrievalUrlRequest( + name="name_value", + ) + + # Make the request + response = client.generate_retrieval_url(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GenerateRetrievalUrl_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_annotation_async.py new file mode 100644 index 000000000000..2bf4e8c5d7ed --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_annotation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_annotation_sync.py new file mode 100644 index 000000000000..adafce9c4180 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_annotation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = client.get_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_asset_async.py new file mode 100644 index 000000000000..99d5f3a9b557 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_asset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_asset_sync.py new file mode 100644 index 000000000000..8f01f3e57b90 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_asset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = client.get_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_collection_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_collection_async.py new file mode 100644 index 000000000000..75a7989abbd7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_collection_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetCollection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetCollectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_collection(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetCollection_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_collection_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_collection_sync.py new file mode 100644 index 000000000000..59e11067d712 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_collection_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetCollection_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetCollectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_collection(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetCollection_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_corpus_async.py new file mode 100644 index 000000000000..8d717e68b674 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_corpus_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_corpus_sync.py new file mode 100644 index 000000000000..b40f21e781d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_corpus_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = client.get_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_data_schema_async.py new file mode 100644 index 000000000000..ed147b0c3a06 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_data_schema_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_data_schema_sync.py new file mode 100644 index 000000000000..0cee1f104a9c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_data_schema_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_async.py new file mode 100644 index 000000000000..2ed32b614875 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetIndex_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexRequest( + name="name_value", + ) + + # Make the request + response = await client.get_index(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetIndex_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_endpoint_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_endpoint_async.py new file mode 100644 index 000000000000..4f816003ecc8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_endpoint_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetIndexEndpoint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexEndpointRequest( + name="name_value", + ) + + # Make the request + response = await client.get_index_endpoint(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetIndexEndpoint_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_endpoint_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_endpoint_sync.py new file mode 100644 index 000000000000..c75a1386ca60 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_endpoint_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetIndexEndpoint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexEndpointRequest( + name="name_value", + ) + + # Make the request + response = client.get_index_endpoint(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetIndexEndpoint_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_sync.py new file mode 100644 index 000000000000..9e32744f7927 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_index_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetIndex_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetIndexRequest( + name="name_value", + ) + + # Make the request + response = client.get_index(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetIndex_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_config_async.py new file mode 100644 index 000000000000..37579788645a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_config_sync.py new file mode 100644 index 000000000000..982f59e17702 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_hypernym_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_hypernym_async.py new file mode 100644 index 000000000000..e9b860c611de --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_hypernym_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetSearchHypernym_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_get_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchHypernymRequest( + name="name_value", + ) + + # Make the request + response = await client.get_search_hypernym(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetSearchHypernym_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_hypernym_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_hypernym_sync.py new file mode 100644 index 000000000000..a36fde9a97fe --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_get_search_hypernym_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_GetSearchHypernym_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_get_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.GetSearchHypernymRequest( + name="name_value", + ) + + # Make the request + response = client.get_search_hypernym(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_GetSearchHypernym_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_import_assets_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_import_assets_async.py new file mode 100644 index 000000000000..ef61e4721bbf --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_import_assets_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ImportAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_import_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ImportAssetsRequest( + assets_gcs_uri="assets_gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_assets(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_ImportAssets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_import_assets_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_import_assets_sync.py new file mode 100644 index 000000000000..7bd06ed1ef67 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_import_assets_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ImportAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_import_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ImportAssetsRequest( + assets_gcs_uri="assets_gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_assets(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_ImportAssets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_index_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_index_asset_async.py new file mode 100644 index 000000000000..388e69008f68 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_index_asset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for IndexAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_IndexAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_index_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.IndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.index_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_IndexAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_index_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_index_asset_sync.py new file mode 100644 index 000000000000..4b467e63d993 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_index_asset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for IndexAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_IndexAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_index_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.IndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.index_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_IndexAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_ingest_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_ingest_asset_async.py new file mode 100644 index 000000000000..f20565a7ae68 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_ingest_asset_async.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for IngestAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_IngestAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_ingest_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + config = visionai_v1.Config() + config.asset = "asset_value" + + request = visionai_v1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.ingest_asset(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1_generated_Warehouse_IngestAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_ingest_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_ingest_asset_sync.py new file mode 100644 index 000000000000..d1b2342f2dfc --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_ingest_asset_sync.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for IngestAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_IngestAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_ingest_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + config = visionai_v1.Config() + config.asset = "asset_value" + + request = visionai_v1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.ingest_asset(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1_generated_Warehouse_IngestAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_annotations_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_annotations_async.py new file mode 100644 index 000000000000..cf0f50d4d5ce --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_annotations_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnnotations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListAnnotations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_annotations(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListAnnotations_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_annotations_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_annotations_sync.py new file mode 100644 index 000000000000..ec0a8d508a81 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_annotations_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnnotations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListAnnotations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_annotations(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListAnnotations_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_assets_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_assets_async.py new file mode 100644 index 000000000000..239c943ee75a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_assets_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_assets_sync.py new file mode 100644 index 000000000000..37e917faa267 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_collections_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_collections_async.py new file mode 100644 index 000000000000..6978dca26b9d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_collections_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCollections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListCollections_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_collections(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_collections(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListCollections_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_collections_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_collections_sync.py new file mode 100644 index 000000000000..410a2c60228c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_collections_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCollections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListCollections_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_collections(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_collections(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListCollections_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_corpora_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_corpora_async.py new file mode 100644 index 000000000000..13357f1a0b84 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_corpora_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCorpora +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListCorpora_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_corpora(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListCorpora_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_corpora_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_corpora_sync.py new file mode 100644 index 000000000000..446402fba508 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_corpora_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCorpora +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListCorpora_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_corpora(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListCorpora_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_data_schemas_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_data_schemas_async.py new file mode 100644 index 000000000000..b89615bbb05f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_data_schemas_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListDataSchemas_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_data_schemas(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListDataSchemas_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_data_schemas_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_data_schemas_sync.py new file mode 100644 index 000000000000..148e51819d6d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_data_schemas_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListDataSchemas_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_data_schemas(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListDataSchemas_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_index_endpoints_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_index_endpoints_async.py new file mode 100644 index 000000000000..04cd728f8cce --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_index_endpoints_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIndexEndpoints +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListIndexEndpoints_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_index_endpoints(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_index_endpoints(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListIndexEndpoints_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_index_endpoints_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_index_endpoints_sync.py new file mode 100644 index 000000000000..32449e576203 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_index_endpoints_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIndexEndpoints +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListIndexEndpoints_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_index_endpoints(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_index_endpoints(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListIndexEndpoints_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_indexes_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_indexes_async.py new file mode 100644 index 000000000000..52728ff5ba9b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_indexes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIndexes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListIndexes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_indexes(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_indexes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListIndexes_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_indexes_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_indexes_sync.py new file mode 100644 index 000000000000..582026f9b5f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_indexes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIndexes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListIndexes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_indexes(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListIndexesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_indexes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListIndexes_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_configs_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_configs_async.py new file mode 100644 index 000000000000..deb8713d6995 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSearchConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListSearchConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_search_configs(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListSearchConfigs_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_configs_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_configs_sync.py new file mode 100644 index 000000000000..eb1fa1f41eac --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSearchConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListSearchConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_search_configs(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListSearchConfigs_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_hypernyms_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_hypernyms_async.py new file mode 100644 index 000000000000..1388c4fc893b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_hypernyms_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSearchHypernyms +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListSearchHypernyms_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_list_search_hypernyms(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchHypernymsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_hypernyms(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListSearchHypernyms_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_hypernyms_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_hypernyms_sync.py new file mode 100644 index 000000000000..b766c433ec09 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_list_search_hypernyms_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSearchHypernyms +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ListSearchHypernyms_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_list_search_hypernyms(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ListSearchHypernymsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_hypernyms(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ListSearchHypernyms_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_collection_item_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_collection_item_async.py new file mode 100644 index 000000000000..ac16b64b3963 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_collection_item_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCollectionItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_RemoveCollectionItem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_remove_collection_item(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.RemoveCollectionItemRequest( + item=item, + ) + + # Make the request + response = await client.remove_collection_item(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_RemoveCollectionItem_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_collection_item_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_collection_item_sync.py new file mode 100644 index 000000000000..b0b2e5d22c07 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_collection_item_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveCollectionItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_RemoveCollectionItem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_remove_collection_item(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + item = visionai_v1.CollectionItem() + item.collection = "collection_value" + item.type_ = "ASSET" + item.item_resource = "item_resource_value" + + request = visionai_v1.RemoveCollectionItemRequest( + item=item, + ) + + # Make the request + response = client.remove_collection_item(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_RemoveCollectionItem_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_index_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_index_asset_async.py new file mode 100644 index 000000000000..7345fff405bb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_index_asset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveIndexAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_RemoveIndexAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_remove_index_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveIndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_index_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_RemoveIndexAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_index_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_index_asset_sync.py new file mode 100644 index 000000000000..e69be051ad70 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_remove_index_asset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveIndexAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_RemoveIndexAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_remove_index_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.RemoveIndexAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_index_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_RemoveIndexAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_assets_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_assets_async.py new file mode 100644 index 000000000000..e0778b3d0e75 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_SearchAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_search_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_SearchAssets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_assets_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_assets_sync.py new file mode 100644 index 000000000000..2ae669fee16b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_SearchAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_search_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_SearchAssets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_index_endpoint_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_index_endpoint_async.py new file mode 100644 index 000000000000..f031aa8355e5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_index_endpoint_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_SearchIndexEndpoint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_search_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + image_query = visionai_v1.ImageQuery() + image_query.input_image = b'input_image_blob' + + request = visionai_v1.SearchIndexEndpointRequest( + image_query=image_query, + index_endpoint="index_endpoint_value", + ) + + # Make the request + page_result = client.search_index_endpoint(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_SearchIndexEndpoint_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_index_endpoint_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_index_endpoint_sync.py new file mode 100644 index 000000000000..eb3e168dfe1b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_search_index_endpoint_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_SearchIndexEndpoint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_search_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + image_query = visionai_v1.ImageQuery() + image_query.input_image = b'input_image_blob' + + request = visionai_v1.SearchIndexEndpointRequest( + image_query=image_query, + index_endpoint="index_endpoint_value", + ) + + # Make the request + page_result = client.search_index_endpoint(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_SearchIndexEndpoint_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_undeploy_index_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_undeploy_index_async.py new file mode 100644 index 000000000000..37d6125b12de --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_undeploy_index_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeployIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UndeployIndex_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_undeploy_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployIndexRequest( + index_endpoint="index_endpoint_value", + ) + + # Make the request + operation = client.undeploy_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UndeployIndex_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_undeploy_index_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_undeploy_index_sync.py new file mode 100644 index 000000000000..f9b7347f36af --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_undeploy_index_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeployIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UndeployIndex_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_undeploy_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UndeployIndexRequest( + index_endpoint="index_endpoint_value", + ) + + # Make the request + operation = client.undeploy_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UndeployIndex_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_annotation_async.py new file mode 100644 index 000000000000..e61f84d0b599 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_annotation_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_annotation(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnnotationRequest( + ) + + # Make the request + response = await client.update_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_annotation_sync.py new file mode 100644 index 000000000000..74bb16381c94 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_annotation_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_annotation(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAnnotationRequest( + ) + + # Make the request + response = client.update_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_asset_async.py new file mode 100644 index 000000000000..ce9847952ee9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_asset_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAssetRequest( + ) + + # Make the request + response = await client.update_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_asset_sync.py new file mode 100644 index 000000000000..74c511a55246 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_asset_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateAssetRequest( + ) + + # Make the request + response = client.update_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_collection_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_collection_async.py new file mode 100644 index 000000000000..c6ff61fe8828 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_collection_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateCollection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_collection(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateCollectionRequest( + ) + + # Make the request + response = await client.update_collection(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateCollection_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_collection_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_collection_sync.py new file mode 100644 index 000000000000..3646c839dac8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_collection_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateCollection_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_collection(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateCollectionRequest( + ) + + # Make the request + response = client.update_collection(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateCollection_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_corpus_async.py new file mode 100644 index 000000000000..e35786eb85fb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_corpus_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_corpus(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = await client.update_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_corpus_sync.py new file mode 100644 index 000000000000..bad2b0d551cf --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_corpus_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_corpus(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = client.update_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_data_schema_async.py new file mode 100644 index 000000000000..3d9a09534cdb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_data_schema_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_data_schema(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = await client.update_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_data_schema_sync.py new file mode 100644 index 000000000000..1117e2878213 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_data_schema_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_data_schema(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = client.update_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_async.py new file mode 100644 index 000000000000..35d3e1a8f61e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateIndex_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_index(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.UpdateIndexRequest( + index=index, + ) + + # Make the request + operation = client.update_index(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateIndex_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_endpoint_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_endpoint_async.py new file mode 100644 index 000000000000..cbced73fde45 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_endpoint_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateIndexEndpoint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateIndexEndpointRequest( + ) + + # Make the request + operation = client.update_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateIndexEndpoint_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_endpoint_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_endpoint_sync.py new file mode 100644 index 000000000000..8ac8fa1b6f34 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_endpoint_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateIndexEndpoint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateIndexEndpoint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_index_endpoint(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateIndexEndpointRequest( + ) + + # Make the request + operation = client.update_index_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateIndexEndpoint_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_sync.py new file mode 100644 index 000000000000..a808a20cfb53 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_index_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateIndex +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateIndex_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_index(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + index = visionai_v1.Index() + index.entire_corpus = True + + request = visionai_v1.UpdateIndexRequest( + index=index, + ) + + # Make the request + operation = client.update_index(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateIndex_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_config_async.py new file mode 100644 index 000000000000..dba986b78097 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_search_config(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchConfigRequest( + ) + + # Make the request + response = await client.update_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_config_sync.py new file mode 100644 index 000000000000..97bdefa1f0cf --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_search_config(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchConfigRequest( + ) + + # Make the request + response = client.update_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_hypernym_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_hypernym_async.py new file mode 100644 index 000000000000..8f2aa803891d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_hypernym_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateSearchHypernym_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_update_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchHypernymRequest( + ) + + # Make the request + response = await client.update_search_hypernym(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateSearchHypernym_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_hypernym_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_hypernym_sync.py new file mode 100644 index 000000000000..d7f09d604422 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_update_search_hypernym_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSearchHypernym +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UpdateSearchHypernym_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_update_search_hypernym(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UpdateSearchHypernymRequest( + ) + + # Make the request + response = client.update_search_hypernym(request=request) + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UpdateSearchHypernym_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_upload_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_upload_asset_async.py new file mode 100644 index 000000000000..df028fd7c546 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_upload_asset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UploadAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_upload_asset(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.UploadAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.upload_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UploadAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_upload_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_upload_asset_sync.py new file mode 100644 index 000000000000..d6cecf91ec1c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_upload_asset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_UploadAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_upload_asset(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.UploadAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.upload_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1_generated_Warehouse_UploadAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_collection_items_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_collection_items_async.py new file mode 100644 index 000000000000..9a36e597024e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_collection_items_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ViewCollectionItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ViewCollectionItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_view_collection_items(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ViewCollectionItemsRequest( + collection="collection_value", + ) + + # Make the request + page_result = client.view_collection_items(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ViewCollectionItems_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_collection_items_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_collection_items_sync.py new file mode 100644 index 000000000000..a0870e85e221 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_collection_items_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ViewCollectionItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ViewCollectionItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_view_collection_items(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ViewCollectionItemsRequest( + collection="collection_value", + ) + + # Make the request + page_result = client.view_collection_items(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ViewCollectionItems_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_indexed_assets_async.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_indexed_assets_async.py new file mode 100644 index 000000000000..4a360d1ae253 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_indexed_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ViewIndexedAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ViewIndexedAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +async def sample_view_indexed_assets(): + # Create a client + client = visionai_v1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1.ViewIndexedAssetsRequest( + index="index_value", + ) + + # Make the request + page_result = client.view_indexed_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ViewIndexedAssets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_indexed_assets_sync.py b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_indexed_assets_sync.py new file mode 100644 index 000000000000..53f2ef9fb85b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/samples/generated_samples/visionai_v1_generated_warehouse_view_indexed_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ViewIndexedAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1_generated_Warehouse_ViewIndexedAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1 + + +def sample_view_indexed_assets(): + # Create a client + client = visionai_v1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1.ViewIndexedAssetsRequest( + index="index_value", + ) + + # Make the request + page_result = client.view_indexed_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1_generated_Warehouse_ViewIndexedAssets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1/scripts/fixup_visionai_v1_keywords.py b/owl-bot-staging/google-cloud-visionai/v1/scripts/fixup_visionai_v1_keywords.py new file mode 100644 index 000000000000..97dfd9af5401 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/scripts/fixup_visionai_v1_keywords.py @@ -0,0 +1,312 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 visionaiCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'acquire_lease': ('series', 'owner', 'term', 'lease_type', ), + 'add_application_stream_input': ('name', 'application_stream_inputs', 'request_id', ), + 'add_collection_item': ('item', ), + 'analyze_asset': ('name', ), + 'analyze_corpus': ('name', ), + 'batch_run_process': ('parent', 'requests', 'options', 'batch_id', ), + 'clip_asset': ('name', 'temporal_partition', ), + 'create_analysis': ('parent', 'analysis_id', 'analysis', 'request_id', ), + 'create_annotation': ('parent', 'annotation', 'annotation_id', ), + 'create_application': ('parent', 'application_id', 'application', 'request_id', ), + 'create_application_instances': ('name', 'application_instances', 'request_id', ), + 'create_asset': ('parent', 'asset', 'asset_id', ), + 'create_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', ), + 'create_collection': ('parent', 'collection', 'collection_id', ), + 'create_corpus': ('parent', 'corpus', ), + 'create_data_schema': ('parent', 'data_schema', ), + 'create_draft': ('parent', 'draft_id', 'draft', 'request_id', ), + 'create_event': ('parent', 'event_id', 'event', 'request_id', ), + 'create_index': ('parent', 'index', 'index_id', ), + 'create_index_endpoint': ('parent', 'index_endpoint', 'index_endpoint_id', ), + 'create_operator': ('parent', 'operator_id', 'operator', 'request_id', ), + 'create_process': ('parent', 'process_id', 'process', 'request_id', ), + 'create_processor': ('parent', 'processor_id', 'processor', 'request_id', ), + 'create_search_config': ('parent', 'search_config', 'search_config_id', ), + 'create_search_hypernym': ('parent', 'search_hypernym', 'search_hypernym_id', ), + 'create_series': ('parent', 'series_id', 'series', 'request_id', ), + 'create_stream': ('parent', 'stream_id', 'stream', 'request_id', ), + 'delete_analysis': ('name', 'request_id', ), + 'delete_annotation': ('name', ), + 'delete_application': ('name', 'request_id', 'force', ), + 'delete_application_instances': ('name', 'instance_ids', 'request_id', ), + 'delete_asset': ('name', ), + 'delete_cluster': ('name', 'request_id', ), + 'delete_collection': ('name', ), + 'delete_corpus': ('name', ), + 'delete_data_schema': ('name', ), + 'delete_draft': ('name', 'request_id', ), + 'delete_event': ('name', 'request_id', ), + 'delete_index': ('name', ), + 'delete_index_endpoint': ('name', ), + 'delete_operator': ('name', 'request_id', ), + 'delete_process': ('name', 'request_id', ), + 'delete_processor': ('name', 'request_id', ), + 'delete_search_config': ('name', ), + 'delete_search_hypernym': ('name', ), + 'delete_series': ('name', 'request_id', ), + 'delete_stream': ('name', 'request_id', ), + 'deploy_application': ('name', 'validate_only', 'request_id', 'enable_monitoring', ), + 'deploy_index': ('index_endpoint', 'deployed_index', ), + 'generate_hls_uri': ('name', 'temporal_partitions', 'live_view_enabled', ), + 'generate_retrieval_url': ('name', ), + 'generate_stream_hls_token': ('stream', ), + 'get_analysis': ('name', ), + 'get_annotation': ('name', ), + 'get_application': ('name', ), + 'get_asset': ('name', ), + 'get_cluster': ('name', ), + 'get_collection': ('name', ), + 'get_corpus': ('name', ), + 'get_data_schema': ('name', ), + 'get_draft': ('name', ), + 'get_event': ('name', ), + 'get_index': ('name', ), + 'get_index_endpoint': ('name', ), + 'get_instance': ('name', ), + 'get_operator': ('name', ), + 'get_process': ('name', ), + 'get_processor': ('name', ), + 'get_search_config': ('name', ), + 'get_search_hypernym': ('name', ), + 'get_series': ('name', ), + 'get_stream': ('name', ), + 'get_stream_thumbnail': ('stream', 'gcs_object_name', 'event', 'request_id', ), + 'health_check': ('cluster', ), + 'import_assets': ('parent', 'assets_gcs_uri', ), + 'index_asset': ('name', 'index', ), + 'ingest_asset': ('config', 'time_indexed_data', ), + 'list_analyses': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_annotations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_applications': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_assets': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_collections': ('parent', 'page_size', 'page_token', ), + 'list_corpora': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_data_schemas': ('parent', 'page_size', 'page_token', ), + 'list_drafts': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_events': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_index_endpoints': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_indexes': ('parent', 'page_size', 'page_token', ), + 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_operators': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_prebuilt_processors': ('parent', ), + 'list_processes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_processors': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_public_operators': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_search_configs': ('parent', 'page_size', 'page_token', ), + 'list_search_hypernyms': ('parent', 'page_size', 'page_token', ), + 'list_series': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_streams': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'materialize_channel': ('parent', 'channel_id', 'channel', 'request_id', ), + 'receive_events': ('setup_request', 'commit_request', ), + 'receive_packets': ('setup_request', 'commit_request', ), + 'release_lease': ('id', 'series', 'owner', ), + 'remove_application_stream_input': ('name', 'target_stream_inputs', 'request_id', ), + 'remove_collection_item': ('item', ), + 'remove_index_asset': ('name', 'index', ), + 'renew_lease': ('id', 'series', 'owner', 'term', ), + 'resolve_operator_info': ('parent', 'queries', ), + 'search_assets': ('corpus', 'schema_key_sorting_strategy', 'page_size', 'page_token', 'content_time_ranges', 'criteria', 'facet_selections', 'result_annotation_keys', 'search_query', ), + 'search_index_endpoint': ('index_endpoint', 'image_query', 'text_query', 'criteria', 'exclusion_criteria', 'page_size', 'page_token', ), + 'send_packets': ('packet', 'metadata', ), + 'undeploy_application': ('name', 'request_id', ), + 'undeploy_index': ('index_endpoint', ), + 'update_analysis': ('update_mask', 'analysis', 'request_id', ), + 'update_annotation': ('annotation', 'update_mask', ), + 'update_application': ('application', 'update_mask', 'request_id', ), + 'update_application_instances': ('name', 'application_instances', 'request_id', 'allow_missing', ), + 'update_application_stream_input': ('name', 'application_stream_inputs', 'request_id', 'allow_missing', ), + 'update_asset': ('asset', 'update_mask', ), + 'update_cluster': ('update_mask', 'cluster', 'request_id', ), + 'update_collection': ('collection', 'update_mask', ), + 'update_corpus': ('corpus', 'update_mask', ), + 'update_data_schema': ('data_schema', 'update_mask', ), + 'update_draft': ('draft', 'update_mask', 'request_id', 'allow_missing', ), + 'update_event': ('update_mask', 'event', 'request_id', ), + 'update_index': ('index', 'update_mask', ), + 'update_index_endpoint': ('index_endpoint', 'update_mask', ), + 'update_operator': ('update_mask', 'operator', 'request_id', ), + 'update_process': ('update_mask', 'process', 'request_id', ), + 'update_processor': ('processor', 'update_mask', 'request_id', ), + 'update_search_config': ('search_config', 'update_mask', ), + 'update_search_hypernym': ('search_hypernym', 'update_mask', ), + 'update_series': ('update_mask', 'series', 'request_id', ), + 'update_stream': ('update_mask', 'stream', 'request_id', ), + 'upload_asset': ('name', 'asset_source', ), + 'view_collection_items': ('collection', 'page_size', 'page_token', ), + 'view_indexed_assets': ('index', 'page_size', 'page_token', 'filter', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=visionaiCallTransformer(), +): + """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 visionai 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/google-cloud-visionai/v1/setup.py b/owl-bot-staging/google-cloud-visionai/v1/setup.py new file mode 100644 index 000000000000..133b5127863d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/setup.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-visionai' + + +description = "Google Cloud Visionai API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/visionai/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-visionai" + +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() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..4cd2782277d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1/tests/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/__init__.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_app_platform.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_app_platform.py new file mode 100644 index 000000000000..3e94bc4478fa --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_app_platform.py @@ -0,0 +1,20351 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1.services.app_platform import AppPlatformAsyncClient +from google.cloud.visionai_v1.services.app_platform import AppPlatformClient +from google.cloud.visionai_v1.services.app_platform import pagers +from google.cloud.visionai_v1.services.app_platform import transports +from google.cloud.visionai_v1.types import annotations +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 AppPlatformClient._get_default_mtls_endpoint(None) is None + assert AppPlatformClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AppPlatformClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AppPlatformClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AppPlatformClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AppPlatformClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AppPlatformClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AppPlatformClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AppPlatformClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AppPlatformClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AppPlatformClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AppPlatformClient._get_client_cert_source(None, False) is None + assert AppPlatformClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AppPlatformClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AppPlatformClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AppPlatformClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AppPlatformClient._DEFAULT_UNIVERSE + default_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AppPlatformClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AppPlatformClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AppPlatformClient.DEFAULT_MTLS_ENDPOINT + assert AppPlatformClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AppPlatformClient._get_api_endpoint(None, None, default_universe, "always") == AppPlatformClient.DEFAULT_MTLS_ENDPOINT + assert AppPlatformClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AppPlatformClient.DEFAULT_MTLS_ENDPOINT + assert AppPlatformClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AppPlatformClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AppPlatformClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AppPlatformClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AppPlatformClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AppPlatformClient._get_universe_domain(None, None) == AppPlatformClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AppPlatformClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AppPlatformClient, "grpc"), + (AppPlatformAsyncClient, "grpc_asyncio"), + (AppPlatformClient, "rest"), +]) +def test_app_platform_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AppPlatformGrpcTransport, "grpc"), + (transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AppPlatformRestTransport, "rest"), +]) +def test_app_platform_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AppPlatformClient, "grpc"), + (AppPlatformAsyncClient, "grpc_asyncio"), + (AppPlatformClient, "rest"), +]) +def test_app_platform_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_app_platform_client_get_transport_class(): + transport = AppPlatformClient.get_transport_class() + available_transports = [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformRestTransport, + ] + assert transport in available_transports + + transport = AppPlatformClient.get_transport_class("grpc") + assert transport == transports.AppPlatformGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest"), +]) +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +def test_app_platform_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(AppPlatformClient, '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(AppPlatformClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", "true"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", "false"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest", "true"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest", "false"), +]) +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_app_platform_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AppPlatformClient, AppPlatformAsyncClient +]) +@mock.patch.object(AppPlatformClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AppPlatformAsyncClient)) +def test_app_platform_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AppPlatformClient, AppPlatformAsyncClient +]) +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +def test_app_platform_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AppPlatformClient._DEFAULT_UNIVERSE + default_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest"), +]) +def test_app_platform_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", grpc_helpers), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest", None), +]) +def test_app_platform_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_app_platform_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1.services.app_platform.transports.AppPlatformGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AppPlatformClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", grpc_helpers), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_app_platform_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListApplicationsRequest, + dict, +]) +def test_list_applications(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListApplicationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApplicationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_applications_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 = AppPlatformClient( + 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_applications), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_applications() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListApplicationsRequest() + + +def test_list_applications_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListApplicationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_applications(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListApplicationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_applications_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_applications in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_applications] = mock_rpc + request = {} + client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applications(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_applications_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_applications() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListApplicationsRequest() + +@pytest.mark.asyncio +async def test_list_applications_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_applications in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_applications] = mock_object + + request = {} + await client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_applications(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_applications_async(transport: str = 'grpc_asyncio', request_type=platform.ListApplicationsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListApplicationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApplicationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_applications_async_from_dict(): + await test_list_applications_async(request_type=dict) + + +def test_list_applications_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListApplicationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + call.return_value = platform.ListApplicationsResponse() + client.list_applications(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_applications_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListApplicationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse()) + await client.list_applications(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_applications_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListApplicationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_applications( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_applications_flattened_error(): + client = AppPlatformClient( + 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_applications( + platform.ListApplicationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_applications_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListApplicationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_applications( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_applications_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_applications( + platform.ListApplicationsRequest(), + parent='parent_value', + ) + + +def test_list_applications_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_applications(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Application) + for i in results) +def test_list_applications_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + pages = list(client.list_applications(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_applications_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_applications(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Application) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_applications_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_applications(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.GetApplicationRequest, + dict, +]) +def test_get_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + billing_mode=platform.Application.BillingMode.PAYG, + ) + response = client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Application) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Application.State.CREATED + assert response.billing_mode == platform.Application.BillingMode.PAYG + + +def test_get_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetApplicationRequest() + + +def test_get_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetApplicationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetApplicationRequest( + name='name_value', + ) + +def test_get_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_application] = mock_rpc + request = {} + client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + billing_mode=platform.Application.BillingMode.PAYG, + )) + response = await client.get_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetApplicationRequest() + +@pytest.mark.asyncio +async def test_get_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_application] = mock_object + + request = {} + await client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_application_async(transport: str = 'grpc_asyncio', request_type=platform.GetApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + billing_mode=platform.Application.BillingMode.PAYG, + )) + response = await client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Application) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Application.State.CREATED + assert response.billing_mode == platform.Application.BillingMode.PAYG + + +@pytest.mark.asyncio +async def test_get_application_async_from_dict(): + await test_get_application_async(request_type=dict) + + +def test_get_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value = platform.Application() + client.get_application(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_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Application()) + await client.get_application(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_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Application() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.GetApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Application() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Application()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.GetApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationRequest, + dict, +]) +def test_create_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationRequest() + + +def test_create_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateApplicationRequest( + parent='parent_value', + application_id='application_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationRequest( + parent='parent_value', + application_id='application_id_value', + request_id='request_id_value', + ) + +def test_create_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application] = mock_rpc + request = {} + client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationRequest() + +@pytest.mark.asyncio +async def test_create_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_application] = mock_object + + request = {} + await client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_async(transport: str = 'grpc_asyncio', request_type=platform.CreateApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_application_async_from_dict(): + await test_create_application_async(request_type=dict) + + +def test_create_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_application(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_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_application(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_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_application( + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + + +def test_create_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.CreateApplicationRequest(), + parent='parent_value', + application=platform.Application(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_application( + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.CreateApplicationRequest(), + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationRequest, + dict, +]) +def test_update_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationRequest() + + +def test_update_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateApplicationRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationRequest( + request_id='request_id_value', + ) + +def test_update_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application] = mock_rpc + request = {} + client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationRequest() + +@pytest.mark.asyncio +async def test_update_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_application] = mock_object + + request = {} + await client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_application_async_from_dict(): + await test_update_application_async(request_type=dict) + + +def test_update_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationRequest() + + request.application.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_application(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', + 'application.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationRequest() + + request.application.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_application(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', + 'application.name=name_value', + ) in kw['metadata'] + + +def test_update_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_application( + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.UpdateApplicationRequest(), + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_application( + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.UpdateApplicationRequest(), + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationRequest, + dict, +]) +def test_delete_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationRequest() + + +def test_delete_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application] = mock_rpc + request = {} + client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationRequest() + +@pytest.mark.asyncio +async def test_delete_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_application] = mock_object + + request = {} + await client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_application_async_from_dict(): + await test_delete_application_async(request_type=dict) + + +def test_delete_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_application(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_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_application(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_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.DeleteApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.DeleteApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeployApplicationRequest, + dict, +]) +def test_deploy_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_deploy_application_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 = AppPlatformClient( + 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.deploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.deploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeployApplicationRequest() + + +def test_deploy_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.deploy_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_deploy_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.deploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.deploy_application] = mock_rpc + request = {} + client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.deploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_deploy_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.deploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeployApplicationRequest() + +@pytest.mark.asyncio +async def test_deploy_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.deploy_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.deploy_application] = mock_object + + request = {} + await client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.deploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_deploy_application_async(transport: str = 'grpc_asyncio', request_type=platform.DeployApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_deploy_application_async_from_dict(): + await test_deploy_application_async(request_type=dict) + + +def test_deploy_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.deploy_application(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_deploy_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.deploy_application(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_deploy_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.deploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_deploy_application_flattened_error(): + client = AppPlatformClient( + 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.deploy_application( + platform.DeployApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_deploy_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.deploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_deploy_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.deploy_application( + platform.DeployApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UndeployApplicationRequest, + dict, +]) +def test_undeploy_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UndeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_undeploy_application_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 = AppPlatformClient( + 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.undeploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.undeploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UndeployApplicationRequest() + + +def test_undeploy_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UndeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.undeploy_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UndeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_undeploy_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.undeploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undeploy_application] = mock_rpc + request = {} + client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.undeploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_undeploy_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.undeploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UndeployApplicationRequest() + +@pytest.mark.asyncio +async def test_undeploy_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.undeploy_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.undeploy_application] = mock_object + + request = {} + await client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.undeploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_undeploy_application_async(transport: str = 'grpc_asyncio', request_type=platform.UndeployApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UndeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_undeploy_application_async_from_dict(): + await test_undeploy_application_async(request_type=dict) + + +def test_undeploy_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UndeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.undeploy_application(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_undeploy_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UndeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.undeploy_application(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_undeploy_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.undeploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_undeploy_application_flattened_error(): + client = AppPlatformClient( + 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.undeploy_application( + platform.UndeployApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_undeploy_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.undeploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_undeploy_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.undeploy_application( + platform.UndeployApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.AddApplicationStreamInputRequest, + dict, +]) +def test_add_application_stream_input(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.AddApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_application_stream_input_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 = AppPlatformClient( + 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.add_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.AddApplicationStreamInputRequest() + + +def test_add_application_stream_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.AddApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_application_stream_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.AddApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_add_application_stream_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_application_stream_input] = mock_rpc + request = {} + client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_add_application_stream_input_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.add_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.AddApplicationStreamInputRequest() + +@pytest.mark.asyncio +async def test_add_application_stream_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.add_application_stream_input in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.add_application_stream_input] = mock_object + + request = {} + await client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.add_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_add_application_stream_input_async(transport: str = 'grpc_asyncio', request_type=platform.AddApplicationStreamInputRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.AddApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_application_stream_input_async_from_dict(): + await test_add_application_stream_input_async(request_type=dict) + + +def test_add_application_stream_input_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.AddApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_application_stream_input(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_add_application_stream_input_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.AddApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_application_stream_input(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_add_application_stream_input_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_add_application_stream_input_flattened_error(): + client = AppPlatformClient( + 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.add_application_stream_input( + platform.AddApplicationStreamInputRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_add_application_stream_input_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_application_stream_input_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.add_application_stream_input( + platform.AddApplicationStreamInputRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.RemoveApplicationStreamInputRequest, + dict, +]) +def test_remove_application_stream_input(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.RemoveApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_application_stream_input_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 = AppPlatformClient( + 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.remove_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.RemoveApplicationStreamInputRequest() + + +def test_remove_application_stream_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.RemoveApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_application_stream_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.RemoveApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_remove_application_stream_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_application_stream_input] = mock_rpc + request = {} + client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_application_stream_input_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.remove_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.RemoveApplicationStreamInputRequest() + +@pytest.mark.asyncio +async def test_remove_application_stream_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.remove_application_stream_input in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.remove_application_stream_input] = mock_object + + request = {} + await client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.remove_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_application_stream_input_async(transport: str = 'grpc_asyncio', request_type=platform.RemoveApplicationStreamInputRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.RemoveApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_application_stream_input_async_from_dict(): + await test_remove_application_stream_input_async(request_type=dict) + + +def test_remove_application_stream_input_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.RemoveApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_application_stream_input(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_remove_application_stream_input_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.RemoveApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_application_stream_input(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_remove_application_stream_input_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_remove_application_stream_input_flattened_error(): + client = AppPlatformClient( + 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.remove_application_stream_input( + platform.RemoveApplicationStreamInputRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_remove_application_stream_input_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_application_stream_input_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.remove_application_stream_input( + platform.RemoveApplicationStreamInputRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationStreamInputRequest, + dict, +]) +def test_update_application_stream_input(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_application_stream_input_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 = AppPlatformClient( + 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_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationStreamInputRequest() + + +def test_update_application_stream_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_stream_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_update_application_stream_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_stream_input] = mock_rpc + request = {} + client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_stream_input_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationStreamInputRequest() + +@pytest.mark.asyncio +async def test_update_application_stream_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_application_stream_input in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_application_stream_input] = mock_object + + request = {} + await client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_stream_input_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateApplicationStreamInputRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_application_stream_input_async_from_dict(): + await test_update_application_stream_input_async(request_type=dict) + + +def test_update_application_stream_input_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_application_stream_input(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_application_stream_input_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_application_stream_input(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_application_stream_input_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_update_application_stream_input_flattened_error(): + client = AppPlatformClient( + 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_application_stream_input( + platform.UpdateApplicationStreamInputRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_update_application_stream_input_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_application_stream_input_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_stream_input( + platform.UpdateApplicationStreamInputRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListInstancesRequest, + dict, +]) +def test_list_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_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 = AppPlatformClient( + 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_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListInstancesRequest() + + +def test_list_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListInstancesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListInstancesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListInstancesRequest() + +@pytest.mark.asyncio +async def test_list_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_instances] = mock_object + + request = {} + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_instances_async(transport: str = 'grpc_asyncio', request_type=platform.ListInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = platform.ListInstancesResponse() + client.list_instances(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_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse()) + await client.list_instances(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_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_instances_flattened_error(): + client = AppPlatformClient( + 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_instances( + platform.ListInstancesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_instances( + platform.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instances(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Instance) + for i in results) +def test_list_instances_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(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_instances_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Instance) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_instances(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.GetInstanceRequest, + dict, +]) +def test_get_instance(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + instance_type=platform.Instance.InstanceType.STREAMING_PREDICTION, + state=platform.Instance.State.CREATING, + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.instance_type == platform.Instance.InstanceType.STREAMING_PREDICTION + assert response.state == platform.Instance.State.CREATING + + +def test_get_instance_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 = AppPlatformClient( + 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_instance), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetInstanceRequest() + + +def test_get_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetInstanceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetInstanceRequest( + name='name_value', + ) + +def test_get_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_instance_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + instance_type=platform.Instance.InstanceType.STREAMING_PREDICTION, + state=platform.Instance.State.CREATING, + )) + response = await client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetInstanceRequest() + +@pytest.mark.asyncio +async def test_get_instance_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_instance in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_instance] = mock_object + + request = {} + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=platform.GetInstanceRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + instance_type=platform.Instance.InstanceType.STREAMING_PREDICTION, + state=platform.Instance.State.CREATING, + )) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.instance_type == platform.Instance.InstanceType.STREAMING_PREDICTION + assert response.state == platform.Instance.State.CREATING + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = platform.Instance() + client.get_instance(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_instance_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance()) + await client.get_instance(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_instance_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_instance_flattened_error(): + client = AppPlatformClient( + 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_instance( + platform.GetInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_instance_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_instance( + platform.GetInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationInstancesRequest, + dict, +]) +def test_create_application_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_application_instances_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 = AppPlatformClient( + 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_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationInstancesRequest() + + +def test_create_application_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_create_application_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application_instances] = mock_rpc + request = {} + client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationInstancesRequest() + +@pytest.mark.asyncio +async def test_create_application_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_application_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_application_instances] = mock_object + + request = {} + await client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_instances_async(transport: str = 'grpc_asyncio', request_type=platform.CreateApplicationInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_application_instances_async_from_dict(): + await test_create_application_instances_async(request_type=dict) + + +def test_create_application_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_application_instances(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_create_application_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_application_instances(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_create_application_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_create_application_instances_flattened_error(): + client = AppPlatformClient( + 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_application_instances( + platform.CreateApplicationInstancesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_create_application_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_application_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_instances( + platform.CreateApplicationInstancesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationInstancesRequest, + dict, +]) +def test_delete_application_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_application_instances_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 = AppPlatformClient( + 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_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationInstancesRequest() + + +def test_delete_application_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_application_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application_instances] = mock_rpc + request = {} + client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationInstancesRequest() + +@pytest.mark.asyncio +async def test_delete_application_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_application_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_application_instances] = mock_object + + request = {} + await client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_instances_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteApplicationInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_application_instances_async_from_dict(): + await test_delete_application_instances_async(request_type=dict) + + +def test_delete_application_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_application_instances(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_application_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_application_instances(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_application_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_application_instances_flattened_error(): + client = AppPlatformClient( + 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_application_instances( + platform.DeleteApplicationInstancesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_application_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_application_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_instances( + platform.DeleteApplicationInstancesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationInstancesRequest, + dict, +]) +def test_update_application_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_application_instances_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 = AppPlatformClient( + 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_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationInstancesRequest() + + +def test_update_application_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_update_application_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_instances] = mock_rpc + request = {} + client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationInstancesRequest() + +@pytest.mark.asyncio +async def test_update_application_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_application_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_application_instances] = mock_object + + request = {} + await client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_instances_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateApplicationInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_application_instances_async_from_dict(): + await test_update_application_instances_async(request_type=dict) + + +def test_update_application_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_application_instances(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_application_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_application_instances(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_application_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_application_instances( + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].application_instances + mock_val = [platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))] + assert arg == mock_val + + +def test_update_application_instances_flattened_error(): + client = AppPlatformClient( + 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_application_instances( + platform.UpdateApplicationInstancesRequest(), + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + +@pytest.mark.asyncio +async def test_update_application_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_application_instances( + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].application_instances + mock_val = [platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_application_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_instances( + platform.UpdateApplicationInstancesRequest(), + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListDraftsRequest, + dict, +]) +def test_list_drafts(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListDraftsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDraftsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_drafts_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 = AppPlatformClient( + 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_drafts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_drafts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListDraftsRequest() + + +def test_list_drafts_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListDraftsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_drafts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListDraftsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_drafts_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_drafts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_drafts] = mock_rpc + request = {} + client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_drafts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_drafts_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_drafts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListDraftsRequest() + +@pytest.mark.asyncio +async def test_list_drafts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_drafts in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_drafts] = mock_object + + request = {} + await client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_drafts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_drafts_async(transport: str = 'grpc_asyncio', request_type=platform.ListDraftsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListDraftsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDraftsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_drafts_async_from_dict(): + await test_list_drafts_async(request_type=dict) + + +def test_list_drafts_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListDraftsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + call.return_value = platform.ListDraftsResponse() + client.list_drafts(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_drafts_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListDraftsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse()) + await client.list_drafts(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_drafts_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListDraftsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_drafts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_drafts_flattened_error(): + client = AppPlatformClient( + 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_drafts( + platform.ListDraftsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_drafts_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListDraftsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_drafts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_drafts_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_drafts( + platform.ListDraftsRequest(), + parent='parent_value', + ) + + +def test_list_drafts_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_drafts(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Draft) + for i in results) +def test_list_drafts_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + pages = list(client.list_drafts(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_drafts_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_drafts(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Draft) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_drafts_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_drafts(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.GetDraftRequest, + dict, +]) +def test_get_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Draft) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetDraftRequest() + + +def test_get_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetDraftRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetDraftRequest( + name='name_value', + ) + +def test_get_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_draft] = mock_rpc + request = {} + client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetDraftRequest() + +@pytest.mark.asyncio +async def test_get_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_draft] = mock_object + + request = {} + await client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_draft_async(transport: str = 'grpc_asyncio', request_type=platform.GetDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Draft) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_draft_async_from_dict(): + await test_get_draft_async(request_type=dict) + + +def test_get_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + call.return_value = platform.Draft() + client.get_draft(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_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft()) + await client.get_draft(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_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Draft() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.GetDraftRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Draft() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.GetDraftRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateDraftRequest, + dict, +]) +def test_create_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateDraftRequest() + + +def test_create_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateDraftRequest( + parent='parent_value', + draft_id='draft_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateDraftRequest( + parent='parent_value', + draft_id='draft_id_value', + request_id='request_id_value', + ) + +def test_create_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_draft] = mock_rpc + request = {} + client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateDraftRequest() + +@pytest.mark.asyncio +async def test_create_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_draft] = mock_object + + request = {} + await client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_draft_async(transport: str = 'grpc_asyncio', request_type=platform.CreateDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_draft_async_from_dict(): + await test_create_draft_async(request_type=dict) + + +def test_create_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateDraftRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_draft(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_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateDraftRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_draft(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_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_draft( + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].draft_id + mock_val = 'draft_id_value' + assert arg == mock_val + + +def test_create_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.CreateDraftRequest(), + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + +@pytest.mark.asyncio +async def test_create_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_draft( + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].draft_id + mock_val = 'draft_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.CreateDraftRequest(), + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateDraftRequest, + dict, +]) +def test_update_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateDraftRequest() + + +def test_update_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateDraftRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateDraftRequest( + request_id='request_id_value', + ) + +def test_update_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_draft] = mock_rpc + request = {} + client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateDraftRequest() + +@pytest.mark.asyncio +async def test_update_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_draft] = mock_object + + request = {} + await client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_draft_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_draft_async_from_dict(): + await test_update_draft_async(request_type=dict) + + +def test_update_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateDraftRequest() + + request.draft.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_draft(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', + 'draft.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateDraftRequest() + + request.draft.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_draft(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', + 'draft.name=name_value', + ) in kw['metadata'] + + +def test_update_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_draft( + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.UpdateDraftRequest(), + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_draft( + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.UpdateDraftRequest(), + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteDraftRequest, + dict, +]) +def test_delete_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteDraftRequest() + + +def test_delete_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteDraftRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteDraftRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_draft] = mock_rpc + request = {} + client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteDraftRequest() + +@pytest.mark.asyncio +async def test_delete_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_draft] = mock_object + + request = {} + await client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_draft_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_draft_async_from_dict(): + await test_delete_draft_async(request_type=dict) + + +def test_delete_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_draft(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_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_draft(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_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.DeleteDraftRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.DeleteDraftRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListProcessorsRequest, + dict, +]) +def test_list_processors(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_processors_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 = AppPlatformClient( + 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_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListProcessorsRequest() + + +def test_list_processors_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListProcessorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_processors(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListProcessorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_processors_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_processors] = mock_rpc + request = {} + client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_processors_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListProcessorsRequest() + +@pytest.mark.asyncio +async def test_list_processors_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_processors in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_processors] = mock_object + + request = {} + await client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=platform.ListProcessorsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_processors_async_from_dict(): + await test_list_processors_async(request_type=dict) + + +def test_list_processors_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = platform.ListProcessorsResponse() + client.list_processors(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_processors_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse()) + await client.list_processors(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_processors_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListProcessorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_processors_flattened_error(): + client = AppPlatformClient( + 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_processors( + platform.ListProcessorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processors_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListProcessorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_processors_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processors( + platform.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processors(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Processor) + for i in results) +def test_list_processors_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processors(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_processors_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processors(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Processor) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processors_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_processors(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.ListPrebuiltProcessorsRequest, + dict, +]) +def test_list_prebuilt_processors(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListPrebuiltProcessorsResponse( + ) + response = client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListPrebuiltProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.ListPrebuiltProcessorsResponse) + + +def test_list_prebuilt_processors_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 = AppPlatformClient( + 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_prebuilt_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_prebuilt_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListPrebuiltProcessorsRequest() + + +def test_list_prebuilt_processors_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListPrebuiltProcessorsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_prebuilt_processors(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListPrebuiltProcessorsRequest( + parent='parent_value', + ) + +def test_list_prebuilt_processors_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_prebuilt_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_prebuilt_processors] = mock_rpc + request = {} + client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_prebuilt_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse( + )) + response = await client.list_prebuilt_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListPrebuiltProcessorsRequest() + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_prebuilt_processors in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_prebuilt_processors] = mock_object + + request = {} + await client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_prebuilt_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_async(transport: str = 'grpc_asyncio', request_type=platform.ListPrebuiltProcessorsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse( + )) + response = await client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListPrebuiltProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.ListPrebuiltProcessorsResponse) + + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_async_from_dict(): + await test_list_prebuilt_processors_async(request_type=dict) + + +def test_list_prebuilt_processors_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListPrebuiltProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + call.return_value = platform.ListPrebuiltProcessorsResponse() + client.list_prebuilt_processors(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_prebuilt_processors_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListPrebuiltProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse()) + await client.list_prebuilt_processors(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_prebuilt_processors_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListPrebuiltProcessorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_prebuilt_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_prebuilt_processors_flattened_error(): + client = AppPlatformClient( + 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_prebuilt_processors( + platform.ListPrebuiltProcessorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListPrebuiltProcessorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_prebuilt_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_prebuilt_processors( + platform.ListPrebuiltProcessorsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.GetProcessorRequest, + dict, +]) +def test_get_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + supported_instance_types=[platform.Instance.InstanceType.STREAMING_PREDICTION], + ) + response = client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Processor) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.processor_type == platform.Processor.ProcessorType.PRETRAINED + assert response.model_type == platform.ModelType.IMAGE_CLASSIFICATION + assert response.state == platform.Processor.ProcessorState.CREATING + assert response.configuration_typeurl == 'configuration_typeurl_value' + assert response.supported_annotation_types == [annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE] + assert response.supports_post_processing is True + assert response.supported_instance_types == [platform.Instance.InstanceType.STREAMING_PREDICTION] + + +def test_get_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetProcessorRequest() + + +def test_get_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetProcessorRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetProcessorRequest( + name='name_value', + ) + +def test_get_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_processor] = mock_rpc + request = {} + client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + supported_instance_types=[platform.Instance.InstanceType.STREAMING_PREDICTION], + )) + response = await client.get_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetProcessorRequest() + +@pytest.mark.asyncio +async def test_get_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_processor] = mock_object + + request = {} + await client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=platform.GetProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + supported_instance_types=[platform.Instance.InstanceType.STREAMING_PREDICTION], + )) + response = await client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Processor) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.processor_type == platform.Processor.ProcessorType.PRETRAINED + assert response.model_type == platform.ModelType.IMAGE_CLASSIFICATION + assert response.state == platform.Processor.ProcessorState.CREATING + assert response.configuration_typeurl == 'configuration_typeurl_value' + assert response.supported_annotation_types == [annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE] + assert response.supports_post_processing is True + assert response.supported_instance_types == [platform.Instance.InstanceType.STREAMING_PREDICTION] + + +@pytest.mark.asyncio +async def test_get_processor_async_from_dict(): + await test_get_processor_async(request_type=dict) + + +def test_get_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = platform.Processor() + client.get_processor(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_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor()) + await client.get_processor(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_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Processor() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.GetProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Processor() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.GetProcessorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateProcessorRequest, + dict, +]) +def test_create_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateProcessorRequest() + + +def test_create_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateProcessorRequest( + parent='parent_value', + processor_id='processor_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateProcessorRequest( + parent='parent_value', + processor_id='processor_id_value', + request_id='request_id_value', + ) + +def test_create_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_processor] = mock_rpc + request = {} + client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateProcessorRequest() + +@pytest.mark.asyncio +async def test_create_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_processor] = mock_object + + request = {} + await client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=platform.CreateProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_processor_async_from_dict(): + await test_create_processor_async(request_type=dict) + + +def test_create_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_processor(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_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_processor(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_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_processor( + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].processor_id + mock_val = 'processor_id_value' + assert arg == mock_val + + +def test_create_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.CreateProcessorRequest(), + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + +@pytest.mark.asyncio +async def test_create_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_processor( + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].processor_id + mock_val = 'processor_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.CreateProcessorRequest(), + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateProcessorRequest, + dict, +]) +def test_update_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateProcessorRequest() + + +def test_update_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateProcessorRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateProcessorRequest( + request_id='request_id_value', + ) + +def test_update_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_processor] = mock_rpc + request = {} + client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateProcessorRequest() + +@pytest.mark.asyncio +async def test_update_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_processor] = mock_object + + request = {} + await client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_processor_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_processor_async_from_dict(): + await test_update_processor_async(request_type=dict) + + +def test_update_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateProcessorRequest() + + request.processor.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_processor(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', + 'processor.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateProcessorRequest() + + request.processor.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_processor(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', + 'processor.name=name_value', + ) in kw['metadata'] + + +def test_update_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_processor( + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.UpdateProcessorRequest(), + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_processor( + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.UpdateProcessorRequest(), + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteProcessorRequest, + dict, +]) +def test_delete_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteProcessorRequest() + + +def test_delete_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteProcessorRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteProcessorRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_processor] = mock_rpc + request = {} + client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteProcessorRequest() + +@pytest.mark.asyncio +async def test_delete_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_processor] = mock_object + + request = {} + await client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_processor_async_from_dict(): + await test_delete_processor_async(request_type=dict) + + +def test_delete_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_processor(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_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_processor(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_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.DeleteProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.DeleteProcessorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListApplicationsRequest, + dict, +]) +def test_list_applications_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListApplicationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_applications(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApplicationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_applications_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_applications in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_applications] = mock_rpc + + request = {} + client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applications(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_applications_rest_required_fields(request_type=platform.ListApplicationsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_applications._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_applications._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListApplicationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListApplicationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_applications(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_applications_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_applications._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_applications_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_applications") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_applications") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListApplicationsRequest.pb(platform.ListApplicationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListApplicationsResponse.to_json(platform.ListApplicationsResponse()) + + request = platform.ListApplicationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListApplicationsResponse() + + client.list_applications(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_applications_rest_bad_request(transport: str = 'rest', request_type=platform.ListApplicationsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_applications(request) + + +def test_list_applications_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListApplicationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListApplicationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_applications(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/applications" % client.transport._host, args[1]) + + +def test_list_applications_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_applications( + platform.ListApplicationsRequest(), + parent='parent_value', + ) + + +def test_list_applications_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListApplicationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_applications(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Application) + for i in results) + + pages = list(client.list_applications(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.GetApplicationRequest, + dict, +]) +def test_get_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + billing_mode=platform.Application.BillingMode.PAYG, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Application.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_application(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Application) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Application.State.CREATED + assert response.billing_mode == platform.Application.BillingMode.PAYG + +def test_get_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_application] = mock_rpc + + request = {} + client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_application_rest_required_fields(request_type=platform.GetApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Application() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Application.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetApplicationRequest.pb(platform.GetApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Application.to_json(platform.Application()) + + request = platform.GetApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Application() + + client.get_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_application_rest_bad_request(transport: str = 'rest', request_type=platform.GetApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_application(request) + + +def test_get_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Application() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Application.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}" % client.transport._host, args[1]) + + +def test_get_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_application( + platform.GetApplicationRequest(), + name='name_value', + ) + + +def test_get_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationRequest, + dict, +]) +def test_create_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["application"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True, 'dynamic_config_input_topic': 'dynamic_config_input_topic_value'}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'gcs_output_config': {'gcs_path': 'gcs_path_value'}, 'product_recognizer_config': {'retail_endpoint': 'retail_endpoint_value', 'recognition_confidence_threshold': 0.3386}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}, 'tag_recognizer_config': {'entity_detection_confidence_threshold': 0.3924, 'tag_parsing_config': {'entity_parsing_configs': [{'entity_class': 'entity_class_value', 'regex': 'regex_value', 'entity_matching_strategy': 1}]}}, 'universal_input_config': {}, 'experimental_config': {'fields': {}}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}, 'runtime_info': {'deploy_time': {}, 'global_output_resources': [{'output_resource': 'output_resource_value', 'producer_node': 'producer_node_value', 'key': 'key_value'}], 'monitoring_config': {'enabled': True}}, 'state': 1, 'billing_mode': 1} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.CreateApplicationRequest.meta.fields["application"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["application"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["application"][field])): + del request_init["application"][field][i][subfield] + else: + del request_init["application"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application] = mock_rpc + + request = {} + client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_application_rest_required_fields(request_type=platform.CreateApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["application_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "applicationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "applicationId" in jsonified_request + assert jsonified_request["applicationId"] == request_init["application_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["applicationId"] = 'application_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("application_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "applicationId" in jsonified_request + assert jsonified_request["applicationId"] == 'application_id_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_application(request) + + expected_params = [ + ( + "applicationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(("applicationId", "requestId", )) & set(("parent", "applicationId", "application", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateApplicationRequest.pb(platform.CreateApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_application_rest_bad_request(transport: str = 'rest', request_type=platform.CreateApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_application(request) + + +def test_create_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + application=platform.Application(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/applications" % client.transport._host, args[1]) + + +def test_create_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_application( + platform.CreateApplicationRequest(), + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + +def test_create_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationRequest, + dict, +]) +def test_update_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'application': {'name': 'projects/sample1/locations/sample2/applications/sample3'}} + request_init["application"] = {'name': 'projects/sample1/locations/sample2/applications/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True, 'dynamic_config_input_topic': 'dynamic_config_input_topic_value'}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'gcs_output_config': {'gcs_path': 'gcs_path_value'}, 'product_recognizer_config': {'retail_endpoint': 'retail_endpoint_value', 'recognition_confidence_threshold': 0.3386}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}, 'tag_recognizer_config': {'entity_detection_confidence_threshold': 0.3924, 'tag_parsing_config': {'entity_parsing_configs': [{'entity_class': 'entity_class_value', 'regex': 'regex_value', 'entity_matching_strategy': 1}]}}, 'universal_input_config': {}, 'experimental_config': {'fields': {}}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}, 'runtime_info': {'deploy_time': {}, 'global_output_resources': [{'output_resource': 'output_resource_value', 'producer_node': 'producer_node_value', 'key': 'key_value'}], 'monitoring_config': {'enabled': True}}, 'state': 1, 'billing_mode': 1} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.UpdateApplicationRequest.meta.fields["application"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["application"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["application"][field])): + del request_init["application"][field][i][subfield] + else: + del request_init["application"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application] = mock_rpc + + request = {} + client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_application_rest_required_fields(request_type=platform.UpdateApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("application", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateApplicationRequest.pb(platform.UpdateApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_application_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'application': {'name': 'projects/sample1/locations/sample2/applications/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_application(request) + + +def test_update_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'application': {'name': 'projects/sample1/locations/sample2/applications/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{application.name=projects/*/locations/*/applications/*}" % client.transport._host, args[1]) + + +def test_update_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_application( + platform.UpdateApplicationRequest(), + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationRequest, + dict, +]) +def test_delete_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application] = mock_rpc + + request = {} + client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_application_rest_required_fields(request_type=platform.DeleteApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", "requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteApplicationRequest.pb(platform.DeleteApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_application_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_application(request) + + +def test_delete_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}" % client.transport._host, args[1]) + + +def test_delete_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_application( + platform.DeleteApplicationRequest(), + name='name_value', + ) + + +def test_delete_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeployApplicationRequest, + dict, +]) +def test_deploy_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.deploy_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_deploy_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.deploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.deploy_application] = mock_rpc + + request = {} + client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.deploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_deploy_application_rest_required_fields(request_type=platform.DeployApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.deploy_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_deploy_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.deploy_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_deploy_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_deploy_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_deploy_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeployApplicationRequest.pb(platform.DeployApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeployApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.deploy_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_deploy_application_rest_bad_request(transport: str = 'rest', request_type=platform.DeployApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.deploy_application(request) + + +def test_deploy_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.deploy_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:deploy" % client.transport._host, args[1]) + + +def test_deploy_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.deploy_application( + platform.DeployApplicationRequest(), + name='name_value', + ) + + +def test_deploy_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UndeployApplicationRequest, + dict, +]) +def test_undeploy_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.undeploy_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_undeploy_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.undeploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undeploy_application] = mock_rpc + + request = {} + client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.undeploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_undeploy_application_rest_required_fields(request_type=platform.UndeployApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.undeploy_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undeploy_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undeploy_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undeploy_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_undeploy_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_undeploy_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UndeployApplicationRequest.pb(platform.UndeployApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UndeployApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undeploy_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undeploy_application_rest_bad_request(transport: str = 'rest', request_type=platform.UndeployApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undeploy_application(request) + + +def test_undeploy_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.undeploy_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:undeploy" % client.transport._host, args[1]) + + +def test_undeploy_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undeploy_application( + platform.UndeployApplicationRequest(), + name='name_value', + ) + + +def test_undeploy_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.AddApplicationStreamInputRequest, + dict, +]) +def test_add_application_stream_input_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.add_application_stream_input(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_add_application_stream_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_application_stream_input] = mock_rpc + + request = {} + client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_add_application_stream_input_rest_required_fields(request_type=platform.AddApplicationStreamInputRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.add_application_stream_input(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_add_application_stream_input_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.add_application_stream_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_application_stream_input_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_add_application_stream_input") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_add_application_stream_input") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.AddApplicationStreamInputRequest.pb(platform.AddApplicationStreamInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.AddApplicationStreamInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.add_application_stream_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_application_stream_input_rest_bad_request(transport: str = 'rest', request_type=platform.AddApplicationStreamInputRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.add_application_stream_input(request) + + +def test_add_application_stream_input_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.add_application_stream_input(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:addStreamInput" % client.transport._host, args[1]) + + +def test_add_application_stream_input_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_application_stream_input( + platform.AddApplicationStreamInputRequest(), + name='name_value', + ) + + +def test_add_application_stream_input_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.RemoveApplicationStreamInputRequest, + dict, +]) +def test_remove_application_stream_input_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.remove_application_stream_input(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_remove_application_stream_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_application_stream_input] = mock_rpc + + request = {} + client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_application_stream_input_rest_required_fields(request_type=platform.RemoveApplicationStreamInputRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.remove_application_stream_input(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_application_stream_input_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_application_stream_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_application_stream_input_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_remove_application_stream_input") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_remove_application_stream_input") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.RemoveApplicationStreamInputRequest.pb(platform.RemoveApplicationStreamInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.RemoveApplicationStreamInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.remove_application_stream_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_application_stream_input_rest_bad_request(transport: str = 'rest', request_type=platform.RemoveApplicationStreamInputRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.remove_application_stream_input(request) + + +def test_remove_application_stream_input_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.remove_application_stream_input(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:removeStreamInput" % client.transport._host, args[1]) + + +def test_remove_application_stream_input_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_application_stream_input( + platform.RemoveApplicationStreamInputRequest(), + name='name_value', + ) + + +def test_remove_application_stream_input_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationStreamInputRequest, + dict, +]) +def test_update_application_stream_input_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_application_stream_input(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_application_stream_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_stream_input] = mock_rpc + + request = {} + client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_application_stream_input_rest_required_fields(request_type=platform.UpdateApplicationStreamInputRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_application_stream_input(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_application_stream_input_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_application_stream_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_application_stream_input_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_application_stream_input") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_application_stream_input") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateApplicationStreamInputRequest.pb(platform.UpdateApplicationStreamInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateApplicationStreamInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_application_stream_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_application_stream_input_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateApplicationStreamInputRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_application_stream_input(request) + + +def test_update_application_stream_input_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_application_stream_input(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:updateStreamInput" % client.transport._host, args[1]) + + +def test_update_application_stream_input_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_application_stream_input( + platform.UpdateApplicationStreamInputRequest(), + name='name_value', + ) + + +def test_update_application_stream_input_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListInstancesRequest, + dict, +]) +def test_list_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_instances_rest_required_fields(request_type=platform.ListInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListInstancesRequest.pb(platform.ListInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListInstancesResponse.to_json(platform.ListInstancesResponse()) + + request = platform.ListInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListInstancesResponse() + + client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_instances_rest_bad_request(transport: str = 'rest', request_type=platform.ListInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_instances(request) + + +def test_list_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/applications/*}/instances" % client.transport._host, args[1]) + + +def test_list_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instances( + platform.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListInstancesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Instance) + for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.GetInstanceRequest, + dict, +]) +def test_get_instance_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/instances/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + instance_type=platform.Instance.InstanceType.STREAMING_PREDICTION, + state=platform.Instance.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.instance_type == platform.Instance.InstanceType.STREAMING_PREDICTION + assert response.state == platform.Instance.State.CREATING + +def test_get_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_instance_rest_required_fields(request_type=platform.GetInstanceRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetInstanceRequest.pb(platform.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Instance.to_json(platform.Instance()) + + request = platform.GetInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Instance() + + client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(transport: str = 'rest', request_type=platform.GetInstanceRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/instances/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_instance(request) + + +def test_get_instance_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3/instances/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*/instances/*}" % client.transport._host, args[1]) + + +def test_get_instance_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + platform.GetInstanceRequest(), + name='name_value', + ) + + +def test_get_instance_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationInstancesRequest, + dict, +]) +def test_create_application_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_application_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_application_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application_instances] = mock_rpc + + request = {} + client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_application_instances_rest_required_fields(request_type=platform.CreateApplicationInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_application_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_application_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_application_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "applicationInstances", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_application_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_application_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_application_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateApplicationInstancesRequest.pb(platform.CreateApplicationInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateApplicationInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_application_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_application_instances_rest_bad_request(transport: str = 'rest', request_type=platform.CreateApplicationInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_application_instances(request) + + +def test_create_application_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_application_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:createApplicationInstances" % client.transport._host, args[1]) + + +def test_create_application_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_application_instances( + platform.CreateApplicationInstancesRequest(), + name='name_value', + ) + + +def test_create_application_instances_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationInstancesRequest, + dict, +]) +def test_delete_application_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_application_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_application_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application_instances] = mock_rpc + + request = {} + client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_application_instances_rest_required_fields(request_type=platform.DeleteApplicationInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request_init["instance_ids"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["instanceIds"] = 'instance_ids_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "instanceIds" in jsonified_request + assert jsonified_request["instanceIds"] == 'instance_ids_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_application_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_application_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_application_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "instanceIds", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_application_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_application_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_application_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteApplicationInstancesRequest.pb(platform.DeleteApplicationInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteApplicationInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_application_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_application_instances_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteApplicationInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_application_instances(request) + + +def test_delete_application_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_application_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:deleteApplicationInstances" % client.transport._host, args[1]) + + +def test_delete_application_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_application_instances( + platform.DeleteApplicationInstancesRequest(), + name='name_value', + ) + + +def test_delete_application_instances_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationInstancesRequest, + dict, +]) +def test_update_application_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_application_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_application_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_instances] = mock_rpc + + request = {} + client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_application_instances_rest_required_fields(request_type=platform.UpdateApplicationInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_application_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_application_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_application_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_application_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_application_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_application_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateApplicationInstancesRequest.pb(platform.UpdateApplicationInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateApplicationInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_application_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_application_instances_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateApplicationInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_application_instances(request) + + +def test_update_application_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_application_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*}:updateApplicationInstances" % client.transport._host, args[1]) + + +def test_update_application_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_application_instances( + platform.UpdateApplicationInstancesRequest(), + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + +def test_update_application_instances_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListDraftsRequest, + dict, +]) +def test_list_drafts_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListDraftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_drafts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDraftsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_drafts_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_drafts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_drafts] = mock_rpc + + request = {} + client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_drafts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_drafts_rest_required_fields(request_type=platform.ListDraftsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_drafts._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_drafts._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListDraftsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListDraftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_drafts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_drafts_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_drafts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_drafts_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_drafts") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_drafts") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListDraftsRequest.pb(platform.ListDraftsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListDraftsResponse.to_json(platform.ListDraftsResponse()) + + request = platform.ListDraftsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListDraftsResponse() + + client.list_drafts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_drafts_rest_bad_request(transport: str = 'rest', request_type=platform.ListDraftsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_drafts(request) + + +def test_list_drafts_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListDraftsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListDraftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_drafts(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/applications/*}/drafts" % client.transport._host, args[1]) + + +def test_list_drafts_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_drafts( + platform.ListDraftsRequest(), + parent='parent_value', + ) + + +def test_list_drafts_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListDraftsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + pager = client.list_drafts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Draft) + for i in results) + + pages = list(client.list_drafts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.GetDraftRequest, + dict, +]) +def test_get_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Draft.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_draft(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Draft) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_draft] = mock_rpc + + request = {} + client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_draft_rest_required_fields(request_type=platform.GetDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Draft() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Draft.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_draft(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetDraftRequest.pb(platform.GetDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Draft.to_json(platform.Draft()) + + request = platform.GetDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Draft() + + client.get_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_draft_rest_bad_request(transport: str = 'rest', request_type=platform.GetDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_draft(request) + + +def test_get_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Draft() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Draft.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*/drafts/*}" % client.transport._host, args[1]) + + +def test_get_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_draft( + platform.GetDraftRequest(), + name='name_value', + ) + + +def test_get_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateDraftRequest, + dict, +]) +def test_create_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request_init["draft"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'draft_application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True, 'dynamic_config_input_topic': 'dynamic_config_input_topic_value'}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'gcs_output_config': {'gcs_path': 'gcs_path_value'}, 'product_recognizer_config': {'retail_endpoint': 'retail_endpoint_value', 'recognition_confidence_threshold': 0.3386}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}, 'tag_recognizer_config': {'entity_detection_confidence_threshold': 0.3924, 'tag_parsing_config': {'entity_parsing_configs': [{'entity_class': 'entity_class_value', 'regex': 'regex_value', 'entity_matching_strategy': 1}]}}, 'universal_input_config': {}, 'experimental_config': {'fields': {}}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.CreateDraftRequest.meta.fields["draft"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["draft"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["draft"][field])): + del request_init["draft"][field][i][subfield] + else: + del request_init["draft"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_draft(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_draft] = mock_rpc + + request = {} + client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_draft_rest_required_fields(request_type=platform.CreateDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["draft_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "draftId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "draftId" in jsonified_request + assert jsonified_request["draftId"] == request_init["draft_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["draftId"] = 'draft_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_draft._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("draft_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "draftId" in jsonified_request + assert jsonified_request["draftId"] == 'draft_id_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_draft(request) + + expected_params = [ + ( + "draftId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(("draftId", "requestId", )) & set(("parent", "draftId", "draft", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateDraftRequest.pb(platform.CreateDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_draft_rest_bad_request(transport: str = 'rest', request_type=platform.CreateDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_draft(request) + + +def test_create_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/applications/*}/drafts" % client.transport._host, args[1]) + + +def test_create_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_draft( + platform.CreateDraftRequest(), + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + +def test_create_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateDraftRequest, + dict, +]) +def test_update_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'draft': {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'}} + request_init["draft"] = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'draft_application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True, 'dynamic_config_input_topic': 'dynamic_config_input_topic_value'}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'gcs_output_config': {'gcs_path': 'gcs_path_value'}, 'product_recognizer_config': {'retail_endpoint': 'retail_endpoint_value', 'recognition_confidence_threshold': 0.3386}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}, 'tag_recognizer_config': {'entity_detection_confidence_threshold': 0.3924, 'tag_parsing_config': {'entity_parsing_configs': [{'entity_class': 'entity_class_value', 'regex': 'regex_value', 'entity_matching_strategy': 1}]}}, 'universal_input_config': {}, 'experimental_config': {'fields': {}}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.UpdateDraftRequest.meta.fields["draft"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["draft"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["draft"][field])): + del request_init["draft"][field][i][subfield] + else: + del request_init["draft"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_draft(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_draft] = mock_rpc + + request = {} + client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_draft_rest_required_fields(request_type=platform.UpdateDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_draft._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_draft(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", )) & set(("draft", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateDraftRequest.pb(platform.UpdateDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_draft_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'draft': {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_draft(request) + + +def test_update_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'draft': {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{draft.name=projects/*/locations/*/applications/*/drafts/*}" % client.transport._host, args[1]) + + +def test_update_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_draft( + platform.UpdateDraftRequest(), + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteDraftRequest, + dict, +]) +def test_delete_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_draft(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_draft] = mock_rpc + + request = {} + client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_draft_rest_required_fields(request_type=platform.DeleteDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_draft._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_draft(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteDraftRequest.pb(platform.DeleteDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_draft_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_draft(request) + + +def test_delete_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/applications/*/drafts/*}" % client.transport._host, args[1]) + + +def test_delete_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_draft( + platform.DeleteDraftRequest(), + name='name_value', + ) + + +def test_delete_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListProcessorsRequest, + dict, +]) +def test_list_processors_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_processors_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_processors] = mock_rpc + + request = {} + client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_processors_rest_required_fields(request_type=platform.ListProcessorsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListProcessorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processors(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processors_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processors._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processors_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_processors") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_processors") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListProcessorsRequest.pb(platform.ListProcessorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListProcessorsResponse.to_json(platform.ListProcessorsResponse()) + + request = platform.ListProcessorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListProcessorsResponse() + + client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=platform.ListProcessorsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processors(request) + + +def test_list_processors_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListProcessorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processors(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_list_processors_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processors( + platform.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListProcessorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_processors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Processor) + for i in results) + + pages = list(client.list_processors(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.ListPrebuiltProcessorsRequest, + dict, +]) +def test_list_prebuilt_processors_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListPrebuiltProcessorsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListPrebuiltProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_prebuilt_processors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.ListPrebuiltProcessorsResponse) + +def test_list_prebuilt_processors_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_prebuilt_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_prebuilt_processors] = mock_rpc + + request = {} + client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_prebuilt_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_prebuilt_processors_rest_required_fields(request_type=platform.ListPrebuiltProcessorsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_prebuilt_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_prebuilt_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListPrebuiltProcessorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListPrebuiltProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_prebuilt_processors(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_prebuilt_processors_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_prebuilt_processors._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_prebuilt_processors_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_prebuilt_processors") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_prebuilt_processors") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListPrebuiltProcessorsRequest.pb(platform.ListPrebuiltProcessorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListPrebuiltProcessorsResponse.to_json(platform.ListPrebuiltProcessorsResponse()) + + request = platform.ListPrebuiltProcessorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListPrebuiltProcessorsResponse() + + client.list_prebuilt_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_prebuilt_processors_rest_bad_request(transport: str = 'rest', request_type=platform.ListPrebuiltProcessorsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_prebuilt_processors(request) + + +def test_list_prebuilt_processors_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListPrebuiltProcessorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListPrebuiltProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_prebuilt_processors(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors:prebuilt" % client.transport._host, args[1]) + + +def test_list_prebuilt_processors_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_prebuilt_processors( + platform.ListPrebuiltProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_prebuilt_processors_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.GetProcessorRequest, + dict, +]) +def test_get_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + supported_instance_types=[platform.Instance.InstanceType.STREAMING_PREDICTION], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Processor) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.processor_type == platform.Processor.ProcessorType.PRETRAINED + assert response.model_type == platform.ModelType.IMAGE_CLASSIFICATION + assert response.state == platform.Processor.ProcessorState.CREATING + assert response.configuration_typeurl == 'configuration_typeurl_value' + assert response.supported_annotation_types == [annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE] + assert response.supports_post_processing is True + assert response.supported_instance_types == [platform.Instance.InstanceType.STREAMING_PREDICTION] + +def test_get_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_processor] = mock_rpc + + request = {} + client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_processor_rest_required_fields(request_type=platform.GetProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Processor() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetProcessorRequest.pb(platform.GetProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Processor.to_json(platform.Processor()) + + request = platform.GetProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Processor() + + client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=platform.GetProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor(request) + + +def test_get_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Processor() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_get_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor( + platform.GetProcessorRequest(), + name='name_value', + ) + + +def test_get_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateProcessorRequest, + dict, +]) +def test_create_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["processor"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'processor_type': 1, 'model_type': 1, 'custom_processor_source_info': {'vertex_model': 'vertex_model_value', 'product_recognizer_artifact': {'retail_product_recognition_index': 'retail_product_recognition_index_value', 'vertex_model': 'vertex_model_value'}, 'source_type': 1, 'additional_info': {}, 'model_schema': {'instances_schema': {'uris': ['uris_value1', 'uris_value2']}, 'parameters_schema': {}, 'predictions_schema': {}}}, 'state': 1, 'processor_io_spec': {'graph_input_channel_specs': [{'name': 'name_value', 'data_type': 1, 'accepted_data_type_uris': ['accepted_data_type_uris_value1', 'accepted_data_type_uris_value2'], 'required': True, 'max_connection_allowed': 2332}], 'graph_output_channel_specs': [{'name': 'name_value', 'data_type': 1, 'data_type_uri': 'data_type_uri_value'}], 'instance_resource_input_binding_specs': [{'config_type_uri': 'config_type_uri_value', 'resource_type_uri': 'resource_type_uri_value', 'name': 'name_value'}], 'instance_resource_output_binding_specs': [{'name': 'name_value', 'resource_type_uri': 'resource_type_uri_value', 'explicit': True}]}, 'configuration_typeurl': 'configuration_typeurl_value', 'supported_annotation_types': [1], 'supports_post_processing': True, 'supported_instance_types': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.CreateProcessorRequest.meta.fields["processor"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["processor"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["processor"][field])): + del request_init["processor"][field][i][subfield] + else: + del request_init["processor"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_processor] = mock_rpc + + request = {} + client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_processor_rest_required_fields(request_type=platform.CreateProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["processor_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "processorId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "processorId" in jsonified_request + assert jsonified_request["processorId"] == request_init["processor_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["processorId"] = 'processor_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("processor_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "processorId" in jsonified_request + assert jsonified_request["processorId"] == 'processor_id_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_processor(request) + + expected_params = [ + ( + "processorId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(("processorId", "requestId", )) & set(("parent", "processorId", "processor", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateProcessorRequest.pb(platform.CreateProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=platform.CreateProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_processor(request) + + +def test_create_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_create_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_processor( + platform.CreateProcessorRequest(), + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + +def test_create_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateProcessorRequest, + dict, +]) +def test_update_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'processor': {'name': 'projects/sample1/locations/sample2/processors/sample3'}} + request_init["processor"] = {'name': 'projects/sample1/locations/sample2/processors/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'processor_type': 1, 'model_type': 1, 'custom_processor_source_info': {'vertex_model': 'vertex_model_value', 'product_recognizer_artifact': {'retail_product_recognition_index': 'retail_product_recognition_index_value', 'vertex_model': 'vertex_model_value'}, 'source_type': 1, 'additional_info': {}, 'model_schema': {'instances_schema': {'uris': ['uris_value1', 'uris_value2']}, 'parameters_schema': {}, 'predictions_schema': {}}}, 'state': 1, 'processor_io_spec': {'graph_input_channel_specs': [{'name': 'name_value', 'data_type': 1, 'accepted_data_type_uris': ['accepted_data_type_uris_value1', 'accepted_data_type_uris_value2'], 'required': True, 'max_connection_allowed': 2332}], 'graph_output_channel_specs': [{'name': 'name_value', 'data_type': 1, 'data_type_uri': 'data_type_uri_value'}], 'instance_resource_input_binding_specs': [{'config_type_uri': 'config_type_uri_value', 'resource_type_uri': 'resource_type_uri_value', 'name': 'name_value'}], 'instance_resource_output_binding_specs': [{'name': 'name_value', 'resource_type_uri': 'resource_type_uri_value', 'explicit': True}]}, 'configuration_typeurl': 'configuration_typeurl_value', 'supported_annotation_types': [1], 'supports_post_processing': True, 'supported_instance_types': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.UpdateProcessorRequest.meta.fields["processor"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["processor"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["processor"][field])): + del request_init["processor"][field][i][subfield] + else: + del request_init["processor"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_processor] = mock_rpc + + request = {} + client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_processor_rest_required_fields(request_type=platform.UpdateProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_processor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("processor", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateProcessorRequest.pb(platform.UpdateProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_processor_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'processor': {'name': 'projects/sample1/locations/sample2/processors/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_processor(request) + + +def test_update_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'processor': {'name': 'projects/sample1/locations/sample2/processors/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{processor.name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_update_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_processor( + platform.UpdateProcessorRequest(), + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteProcessorRequest, + dict, +]) +def test_delete_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_processor] = mock_rpc + + request = {} + client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_processor_rest_required_fields(request_type=platform.DeleteProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteProcessorRequest.pb(platform.DeleteProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_processor(request) + + +def test_delete_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_delete_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_processor( + platform.DeleteProcessorRequest(), + name='name_value', + ) + + +def test_delete_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AppPlatformClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AppPlatformGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformGrpcAsyncIOTransport, + transports.AppPlatformRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = AppPlatformClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AppPlatformGrpcTransport, + ) + +def test_app_platform_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AppPlatformTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_app_platform_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1.services.app_platform.transports.AppPlatformTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AppPlatformTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_applications', + 'get_application', + 'create_application', + 'update_application', + 'delete_application', + 'deploy_application', + 'undeploy_application', + 'add_application_stream_input', + 'remove_application_stream_input', + 'update_application_stream_input', + 'list_instances', + 'get_instance', + 'create_application_instances', + 'delete_application_instances', + 'update_application_instances', + 'list_drafts', + 'get_draft', + 'create_draft', + 'update_draft', + 'delete_draft', + 'list_processors', + 'list_prebuilt_processors', + 'get_processor', + 'create_processor', + 'update_processor', + 'delete_processor', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_app_platform_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1.services.app_platform.transports.AppPlatformTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AppPlatformTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_app_platform_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1.services.app_platform.transports.AppPlatformTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AppPlatformTransport() + adc.assert_called_once() + + +def test_app_platform_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) + AppPlatformClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformGrpcAsyncIOTransport, + ], +) +def test_app_platform_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformGrpcAsyncIOTransport, + transports.AppPlatformRestTransport, + ], +) +def test_app_platform_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AppPlatformGrpcTransport, grpc_helpers), + (transports.AppPlatformGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_app_platform_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( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AppPlatformGrpcTransport, transports.AppPlatformGrpcAsyncIOTransport]) +def test_app_platform_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_app_platform_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.AppPlatformRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_app_platform_rest_lro_client(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_app_platform_host_no_port(transport_name): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_app_platform_host_with_port(transport_name): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_app_platform_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AppPlatformClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AppPlatformClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_applications._session + session2 = client2.transport.list_applications._session + assert session1 != session2 + session1 = client1.transport.get_application._session + session2 = client2.transport.get_application._session + assert session1 != session2 + session1 = client1.transport.create_application._session + session2 = client2.transport.create_application._session + assert session1 != session2 + session1 = client1.transport.update_application._session + session2 = client2.transport.update_application._session + assert session1 != session2 + session1 = client1.transport.delete_application._session + session2 = client2.transport.delete_application._session + assert session1 != session2 + session1 = client1.transport.deploy_application._session + session2 = client2.transport.deploy_application._session + assert session1 != session2 + session1 = client1.transport.undeploy_application._session + session2 = client2.transport.undeploy_application._session + assert session1 != session2 + session1 = client1.transport.add_application_stream_input._session + session2 = client2.transport.add_application_stream_input._session + assert session1 != session2 + session1 = client1.transport.remove_application_stream_input._session + session2 = client2.transport.remove_application_stream_input._session + assert session1 != session2 + session1 = client1.transport.update_application_stream_input._session + session2 = client2.transport.update_application_stream_input._session + assert session1 != session2 + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_application_instances._session + session2 = client2.transport.create_application_instances._session + assert session1 != session2 + session1 = client1.transport.delete_application_instances._session + session2 = client2.transport.delete_application_instances._session + assert session1 != session2 + session1 = client1.transport.update_application_instances._session + session2 = client2.transport.update_application_instances._session + assert session1 != session2 + session1 = client1.transport.list_drafts._session + session2 = client2.transport.list_drafts._session + assert session1 != session2 + session1 = client1.transport.get_draft._session + session2 = client2.transport.get_draft._session + assert session1 != session2 + session1 = client1.transport.create_draft._session + session2 = client2.transport.create_draft._session + assert session1 != session2 + session1 = client1.transport.update_draft._session + session2 = client2.transport.update_draft._session + assert session1 != session2 + session1 = client1.transport.delete_draft._session + session2 = client2.transport.delete_draft._session + assert session1 != session2 + session1 = client1.transport.list_processors._session + session2 = client2.transport.list_processors._session + assert session1 != session2 + session1 = client1.transport.list_prebuilt_processors._session + session2 = client2.transport.list_prebuilt_processors._session + assert session1 != session2 + session1 = client1.transport.get_processor._session + session2 = client2.transport.get_processor._session + assert session1 != session2 + session1 = client1.transport.create_processor._session + session2 = client2.transport.create_processor._session + assert session1 != session2 + session1 = client1.transport.update_processor._session + session2 = client2.transport.update_processor._session + assert session1 != session2 + session1 = client1.transport.delete_processor._session + session2 = client2.transport.delete_processor._session + assert session1 != session2 +def test_app_platform_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AppPlatformGrpcTransport( + 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_app_platform_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AppPlatformGrpcAsyncIOTransport( + 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.AppPlatformGrpcTransport, transports.AppPlatformGrpcAsyncIOTransport]) +def test_app_platform_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.AppPlatformGrpcTransport, transports.AppPlatformGrpcAsyncIOTransport]) +def test_app_platform_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_app_platform_grpc_lro_client(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_app_platform_grpc_lro_async_client(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_application_path(): + project = "squid" + location = "clam" + application = "whelk" + expected = "projects/{project}/locations/{location}/applications/{application}".format(project=project, location=location, application=application, ) + actual = AppPlatformClient.application_path(project, location, application) + assert expected == actual + + +def test_parse_application_path(): + expected = { + "project": "octopus", + "location": "oyster", + "application": "nudibranch", + } + path = AppPlatformClient.application_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_application_path(path) + assert expected == actual + +def test_draft_path(): + project = "cuttlefish" + location = "mussel" + application = "winkle" + draft = "nautilus" + expected = "projects/{project}/locations/{location}/applications/{application}/drafts/{draft}".format(project=project, location=location, application=application, draft=draft, ) + actual = AppPlatformClient.draft_path(project, location, application, draft) + assert expected == actual + + +def test_parse_draft_path(): + expected = { + "project": "scallop", + "location": "abalone", + "application": "squid", + "draft": "clam", + } + path = AppPlatformClient.draft_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_draft_path(path) + assert expected == actual + +def test_instance_path(): + project = "whelk" + location = "octopus" + application = "oyster" + instance = "nudibranch" + expected = "projects/{project}/locations/{location}/applications/{application}/instances/{instance}".format(project=project, location=location, application=application, instance=instance, ) + actual = AppPlatformClient.instance_path(project, location, application, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "application": "winkle", + "instance": "nautilus", + } + path = AppPlatformClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_instance_path(path) + assert expected == actual + +def test_processor_path(): + project = "scallop" + location = "abalone" + processor = "squid" + expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + actual = AppPlatformClient.processor_path(project, location, processor) + assert expected == actual + + +def test_parse_processor_path(): + expected = { + "project": "clam", + "location": "whelk", + "processor": "octopus", + } + path = AppPlatformClient.processor_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_processor_path(path) + assert expected == actual + +def test_stream_path(): + project = "oyster" + location = "nudibranch" + cluster = "cuttlefish" + stream = "mussel" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + actual = AppPlatformClient.stream_path(project, location, cluster, stream) + assert expected == actual + + +def test_parse_stream_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "cluster": "scallop", + "stream": "abalone", + } + path = AppPlatformClient.stream_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_stream_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AppPlatformClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AppPlatformClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AppPlatformClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AppPlatformClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AppPlatformClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AppPlatformClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AppPlatformClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AppPlatformClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AppPlatformClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AppPlatformClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.AppPlatformTransport, '_prep_wrapped_messages') as prep: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AppPlatformTransport, '_prep_wrapped_messages') as prep: + transport_class = AppPlatformClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_health_check_service.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_health_check_service.py new file mode 100644 index 000000000000..d776b2c06f4d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_health_check_service.py @@ -0,0 +1,2565 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1.services.health_check_service import HealthCheckServiceAsyncClient +from google.cloud.visionai_v1.services.health_check_service import HealthCheckServiceClient +from google.cloud.visionai_v1.services.health_check_service import transports +from google.cloud.visionai_v1.types import health_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 HealthCheckServiceClient._get_default_mtls_endpoint(None) is None + assert HealthCheckServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert HealthCheckServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert HealthCheckServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert HealthCheckServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert HealthCheckServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert HealthCheckServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HealthCheckServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert HealthCheckServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + HealthCheckServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert HealthCheckServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert HealthCheckServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert HealthCheckServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + HealthCheckServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert HealthCheckServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert HealthCheckServiceClient._get_client_cert_source(None, False) is None + assert HealthCheckServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert HealthCheckServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert HealthCheckServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert HealthCheckServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(HealthCheckServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceClient)) +@mock.patch.object(HealthCheckServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = HealthCheckServiceClient._DEFAULT_UNIVERSE + default_endpoint = HealthCheckServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = HealthCheckServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert HealthCheckServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert HealthCheckServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == HealthCheckServiceClient.DEFAULT_MTLS_ENDPOINT + assert HealthCheckServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert HealthCheckServiceClient._get_api_endpoint(None, None, default_universe, "always") == HealthCheckServiceClient.DEFAULT_MTLS_ENDPOINT + assert HealthCheckServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == HealthCheckServiceClient.DEFAULT_MTLS_ENDPOINT + assert HealthCheckServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert HealthCheckServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + HealthCheckServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert HealthCheckServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert HealthCheckServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert HealthCheckServiceClient._get_universe_domain(None, None) == HealthCheckServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + HealthCheckServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport, "grpc"), + (HealthCheckServiceClient, transports.HealthCheckServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (HealthCheckServiceClient, "grpc"), + (HealthCheckServiceAsyncClient, "grpc_asyncio"), + (HealthCheckServiceClient, "rest"), +]) +def test_health_check_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.HealthCheckServiceGrpcTransport, "grpc"), + (transports.HealthCheckServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.HealthCheckServiceRestTransport, "rest"), +]) +def test_health_check_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (HealthCheckServiceClient, "grpc"), + (HealthCheckServiceAsyncClient, "grpc_asyncio"), + (HealthCheckServiceClient, "rest"), +]) +def test_health_check_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_health_check_service_client_get_transport_class(): + transport = HealthCheckServiceClient.get_transport_class() + available_transports = [ + transports.HealthCheckServiceGrpcTransport, + transports.HealthCheckServiceRestTransport, + ] + assert transport in available_transports + + transport = HealthCheckServiceClient.get_transport_class("grpc") + assert transport == transports.HealthCheckServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport, "grpc"), + (HealthCheckServiceAsyncClient, transports.HealthCheckServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (HealthCheckServiceClient, transports.HealthCheckServiceRestTransport, "rest"), +]) +@mock.patch.object(HealthCheckServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceClient)) +@mock.patch.object(HealthCheckServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceAsyncClient)) +def test_health_check_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(HealthCheckServiceClient, '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(HealthCheckServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport, "grpc", "true"), + (HealthCheckServiceAsyncClient, transports.HealthCheckServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport, "grpc", "false"), + (HealthCheckServiceAsyncClient, transports.HealthCheckServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (HealthCheckServiceClient, transports.HealthCheckServiceRestTransport, "rest", "true"), + (HealthCheckServiceClient, transports.HealthCheckServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(HealthCheckServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceClient)) +@mock.patch.object(HealthCheckServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_health_check_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + HealthCheckServiceClient, HealthCheckServiceAsyncClient +]) +@mock.patch.object(HealthCheckServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HealthCheckServiceClient)) +@mock.patch.object(HealthCheckServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HealthCheckServiceAsyncClient)) +def test_health_check_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + HealthCheckServiceClient, HealthCheckServiceAsyncClient +]) +@mock.patch.object(HealthCheckServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceClient)) +@mock.patch.object(HealthCheckServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HealthCheckServiceAsyncClient)) +def test_health_check_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = HealthCheckServiceClient._DEFAULT_UNIVERSE + default_endpoint = HealthCheckServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = HealthCheckServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport, "grpc"), + (HealthCheckServiceAsyncClient, transports.HealthCheckServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (HealthCheckServiceClient, transports.HealthCheckServiceRestTransport, "rest"), +]) +def test_health_check_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport, "grpc", grpc_helpers), + (HealthCheckServiceAsyncClient, transports.HealthCheckServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (HealthCheckServiceClient, transports.HealthCheckServiceRestTransport, "rest", None), +]) +def test_health_check_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_health_check_service_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1.services.health_check_service.transports.HealthCheckServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = HealthCheckServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport, "grpc", grpc_helpers), + (HealthCheckServiceAsyncClient, transports.HealthCheckServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_health_check_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + health_service.HealthCheckRequest, + dict, +]) +def test_health_check(request_type, transport: str = 'grpc'): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.health_check), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = health_service.HealthCheckResponse( + healthy=True, + reason='reason_value', + ) + response = client.health_check(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = health_service.HealthCheckRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, health_service.HealthCheckResponse) + assert response.healthy is True + assert response.reason == 'reason_value' + + +def test_health_check_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 = HealthCheckServiceClient( + 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.health_check), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.health_check() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == health_service.HealthCheckRequest() + + +def test_health_check_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = health_service.HealthCheckRequest( + cluster='cluster_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.health_check), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.health_check(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == health_service.HealthCheckRequest( + cluster='cluster_value', + ) + +def test_health_check_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.health_check in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.health_check] = mock_rpc + request = {} + client.health_check(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.health_check(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_health_check_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.health_check), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(health_service.HealthCheckResponse( + healthy=True, + reason='reason_value', + )) + response = await client.health_check() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == health_service.HealthCheckRequest() + +@pytest.mark.asyncio +async def test_health_check_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.health_check in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.health_check] = mock_object + + request = {} + await client.health_check(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.health_check(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_health_check_async(transport: str = 'grpc_asyncio', request_type=health_service.HealthCheckRequest): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.health_check), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(health_service.HealthCheckResponse( + healthy=True, + reason='reason_value', + )) + response = await client.health_check(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = health_service.HealthCheckRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, health_service.HealthCheckResponse) + assert response.healthy is True + assert response.reason == 'reason_value' + + +@pytest.mark.asyncio +async def test_health_check_async_from_dict(): + await test_health_check_async(request_type=dict) + + +def test_health_check_field_headers(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = health_service.HealthCheckRequest() + + request.cluster = 'cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.health_check), + '__call__') as call: + call.return_value = health_service.HealthCheckResponse() + client.health_check(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', + 'cluster=cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_health_check_field_headers_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = health_service.HealthCheckRequest() + + request.cluster = 'cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.health_check), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(health_service.HealthCheckResponse()) + await client.health_check(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', + 'cluster=cluster_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + health_service.HealthCheckRequest, + dict, +]) +def test_health_check_rest(request_type): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = health_service.HealthCheckResponse( + healthy=True, + reason='reason_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = health_service.HealthCheckResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.health_check(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, health_service.HealthCheckResponse) + assert response.healthy is True + assert response.reason == 'reason_value' + +def test_health_check_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.health_check in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.health_check] = mock_rpc + + request = {} + client.health_check(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.health_check(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_health_check_rest_interceptors(null_interceptor): + transport = transports.HealthCheckServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HealthCheckServiceRestInterceptor(), + ) + client = HealthCheckServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.HealthCheckServiceRestInterceptor, "post_health_check") as post, \ + mock.patch.object(transports.HealthCheckServiceRestInterceptor, "pre_health_check") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = health_service.HealthCheckRequest.pb(health_service.HealthCheckRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = health_service.HealthCheckResponse.to_json(health_service.HealthCheckResponse()) + + request = health_service.HealthCheckRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = health_service.HealthCheckResponse() + + client.health_check(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_health_check_rest_bad_request(transport: str = 'rest', request_type=health_service.HealthCheckRequest): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.health_check(request) + + +def test_health_check_rest_error(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.HealthCheckServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.HealthCheckServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HealthCheckServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.HealthCheckServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HealthCheckServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HealthCheckServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.HealthCheckServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HealthCheckServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.HealthCheckServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = HealthCheckServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.HealthCheckServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.HealthCheckServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.HealthCheckServiceGrpcTransport, + transports.HealthCheckServiceGrpcAsyncIOTransport, + transports.HealthCheckServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = HealthCheckServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.HealthCheckServiceGrpcTransport, + ) + +def test_health_check_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.HealthCheckServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_health_check_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1.services.health_check_service.transports.HealthCheckServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.HealthCheckServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'health_check', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_health_check_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1.services.health_check_service.transports.HealthCheckServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HealthCheckServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_health_check_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1.services.health_check_service.transports.HealthCheckServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HealthCheckServiceTransport() + adc.assert_called_once() + + +def test_health_check_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + HealthCheckServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HealthCheckServiceGrpcTransport, + transports.HealthCheckServiceGrpcAsyncIOTransport, + ], +) +def test_health_check_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HealthCheckServiceGrpcTransport, + transports.HealthCheckServiceGrpcAsyncIOTransport, + transports.HealthCheckServiceRestTransport, + ], +) +def test_health_check_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.HealthCheckServiceGrpcTransport, grpc_helpers), + (transports.HealthCheckServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_health_check_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.HealthCheckServiceGrpcTransport, transports.HealthCheckServiceGrpcAsyncIOTransport]) +def test_health_check_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_health_check_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.HealthCheckServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_health_check_service_host_no_port(transport_name): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_health_check_service_host_with_port(transport_name): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_health_check_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = HealthCheckServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = HealthCheckServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.health_check._session + session2 = client2.transport.health_check._session + assert session1 != session2 +def test_health_check_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HealthCheckServiceGrpcTransport( + 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_health_check_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HealthCheckServiceGrpcAsyncIOTransport( + 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.HealthCheckServiceGrpcTransport, transports.HealthCheckServiceGrpcAsyncIOTransport]) +def test_health_check_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.HealthCheckServiceGrpcTransport, transports.HealthCheckServiceGrpcAsyncIOTransport]) +def test_health_check_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_cluster_path(): + project = "squid" + location = "clam" + cluster = "whelk" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = HealthCheckServiceClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "octopus", + "location": "oyster", + "cluster": "nudibranch", + } + path = HealthCheckServiceClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = HealthCheckServiceClient.parse_cluster_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = HealthCheckServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = HealthCheckServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = HealthCheckServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = HealthCheckServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = HealthCheckServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = HealthCheckServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = HealthCheckServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = HealthCheckServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = HealthCheckServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = HealthCheckServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = HealthCheckServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = HealthCheckServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = HealthCheckServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = HealthCheckServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = HealthCheckServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.HealthCheckServiceTransport, '_prep_wrapped_messages') as prep: + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.HealthCheckServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = HealthCheckServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = HealthCheckServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = HealthCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (HealthCheckServiceClient, transports.HealthCheckServiceGrpcTransport), + (HealthCheckServiceAsyncClient, transports.HealthCheckServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_live_video_analytics.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_live_video_analytics.py new file mode 100644 index 000000000000..81d4e64dcec0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_live_video_analytics.py @@ -0,0 +1,15227 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1.services.live_video_analytics import LiveVideoAnalyticsAsyncClient +from google.cloud.visionai_v1.services.live_video_analytics import LiveVideoAnalyticsClient +from google.cloud.visionai_v1.services.live_video_analytics import pagers +from google.cloud.visionai_v1.services.live_video_analytics import transports +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import lva +from google.cloud.visionai_v1.types import lva_resources +from google.cloud.visionai_v1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 LiveVideoAnalyticsClient._get_default_mtls_endpoint(None) is None + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LiveVideoAnalyticsClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LiveVideoAnalyticsClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert LiveVideoAnalyticsClient._get_client_cert_source(None, False) is None + assert LiveVideoAnalyticsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LiveVideoAnalyticsClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert LiveVideoAnalyticsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LiveVideoAnalyticsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + default_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LiveVideoAnalyticsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LiveVideoAnalyticsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, default_universe, "always") == LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + assert LiveVideoAnalyticsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LiveVideoAnalyticsClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert LiveVideoAnalyticsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LiveVideoAnalyticsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LiveVideoAnalyticsClient._get_universe_domain(None, None) == LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LiveVideoAnalyticsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LiveVideoAnalyticsClient, "grpc"), + (LiveVideoAnalyticsAsyncClient, "grpc_asyncio"), + (LiveVideoAnalyticsClient, "rest"), +]) +def test_live_video_analytics_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +def test_live_video_analytics_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LiveVideoAnalyticsClient, "grpc"), + (LiveVideoAnalyticsAsyncClient, "grpc_asyncio"), + (LiveVideoAnalyticsClient, "rest"), +]) +def test_live_video_analytics_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_live_video_analytics_client_get_transport_class(): + transport = LiveVideoAnalyticsClient.get_transport_class() + available_transports = [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsRestTransport, + ] + assert transport in available_transports + + transport = LiveVideoAnalyticsClient.get_transport_class("grpc") + assert transport == transports.LiveVideoAnalyticsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +def test_live_video_analytics_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(LiveVideoAnalyticsClient, '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(LiveVideoAnalyticsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", "true"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", "false"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest", "true"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest", "false"), +]) +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_live_video_analytics_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + LiveVideoAnalyticsClient, LiveVideoAnalyticsAsyncClient +]) +@mock.patch.object(LiveVideoAnalyticsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LiveVideoAnalyticsAsyncClient)) +def test_live_video_analytics_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + LiveVideoAnalyticsClient, LiveVideoAnalyticsAsyncClient +]) +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +def test_live_video_analytics_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + default_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +def test_live_video_analytics_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", grpc_helpers), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest", None), +]) +def test_live_video_analytics_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_live_video_analytics_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1.services.live_video_analytics.transports.LiveVideoAnalyticsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LiveVideoAnalyticsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", grpc_helpers), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_live_video_analytics_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListPublicOperatorsRequest, + dict, +]) +def test_list_public_operators(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_public_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListPublicOperatorsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_public_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.ListPublicOperatorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPublicOperatorsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_public_operators_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 = LiveVideoAnalyticsClient( + 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_public_operators), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_public_operators() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListPublicOperatorsRequest() + + +def test_list_public_operators_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.ListPublicOperatorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_public_operators(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListPublicOperatorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_public_operators_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_public_operators in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_public_operators] = mock_rpc + request = {} + client.list_public_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_public_operators(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_public_operators_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListPublicOperatorsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_public_operators() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListPublicOperatorsRequest() + +@pytest.mark.asyncio +async def test_list_public_operators_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_public_operators in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_public_operators] = mock_object + + request = {} + await client.list_public_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_public_operators(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_public_operators_async(transport: str = 'grpc_asyncio', request_type=lva_service.ListPublicOperatorsRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_public_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListPublicOperatorsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_public_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.ListPublicOperatorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPublicOperatorsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_public_operators_async_from_dict(): + await test_list_public_operators_async(request_type=dict) + + +def test_list_public_operators_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListPublicOperatorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + call.return_value = lva_service.ListPublicOperatorsResponse() + client.list_public_operators(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_public_operators_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListPublicOperatorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListPublicOperatorsResponse()) + await client.list_public_operators(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_public_operators_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListPublicOperatorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_public_operators( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_public_operators_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_public_operators( + lva_service.ListPublicOperatorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_public_operators_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListPublicOperatorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListPublicOperatorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_public_operators( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_public_operators_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_public_operators( + lva_service.ListPublicOperatorsRequest(), + parent='parent_value', + ) + + +def test_list_public_operators_pager(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListPublicOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_public_operators(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Operator) + for i in results) +def test_list_public_operators_pages(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListPublicOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + pages = list(client.list_public_operators(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_public_operators_async_pager(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListPublicOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_public_operators(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, lva_resources.Operator) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_public_operators_async_pages(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_public_operators), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListPublicOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_public_operators(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + lva_service.ResolveOperatorInfoRequest, + dict, +]) +def test_resolve_operator_info(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ResolveOperatorInfoResponse( + ) + response = client.resolve_operator_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.ResolveOperatorInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_service.ResolveOperatorInfoResponse) + + +def test_resolve_operator_info_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 = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.resolve_operator_info() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ResolveOperatorInfoRequest() + + +def test_resolve_operator_info_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.ResolveOperatorInfoRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.resolve_operator_info(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ResolveOperatorInfoRequest( + parent='parent_value', + ) + +def test_resolve_operator_info_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.resolve_operator_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.resolve_operator_info] = mock_rpc + request = {} + client.resolve_operator_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.resolve_operator_info(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_resolve_operator_info_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ResolveOperatorInfoResponse( + )) + response = await client.resolve_operator_info() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ResolveOperatorInfoRequest() + +@pytest.mark.asyncio +async def test_resolve_operator_info_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.resolve_operator_info in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.resolve_operator_info] = mock_object + + request = {} + await client.resolve_operator_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.resolve_operator_info(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_resolve_operator_info_async(transport: str = 'grpc_asyncio', request_type=lva_service.ResolveOperatorInfoRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ResolveOperatorInfoResponse( + )) + response = await client.resolve_operator_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.ResolveOperatorInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_service.ResolveOperatorInfoResponse) + + +@pytest.mark.asyncio +async def test_resolve_operator_info_async_from_dict(): + await test_resolve_operator_info_async(request_type=dict) + + +def test_resolve_operator_info_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ResolveOperatorInfoRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + call.return_value = lva_service.ResolveOperatorInfoResponse() + client.resolve_operator_info(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_resolve_operator_info_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ResolveOperatorInfoRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ResolveOperatorInfoResponse()) + await client.resolve_operator_info(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_resolve_operator_info_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ResolveOperatorInfoResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.resolve_operator_info( + parent='parent_value', + queries=[lva_service.OperatorQuery(operator='operator_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].queries + mock_val = [lva_service.OperatorQuery(operator='operator_value')] + assert arg == mock_val + + +def test_resolve_operator_info_flattened_error(): + client = LiveVideoAnalyticsClient( + 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.resolve_operator_info( + lva_service.ResolveOperatorInfoRequest(), + parent='parent_value', + queries=[lva_service.OperatorQuery(operator='operator_value')], + ) + +@pytest.mark.asyncio +async def test_resolve_operator_info_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resolve_operator_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ResolveOperatorInfoResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ResolveOperatorInfoResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.resolve_operator_info( + parent='parent_value', + queries=[lva_service.OperatorQuery(operator='operator_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].queries + mock_val = [lva_service.OperatorQuery(operator='operator_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_resolve_operator_info_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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.resolve_operator_info( + lva_service.ResolveOperatorInfoRequest(), + parent='parent_value', + queries=[lva_service.OperatorQuery(operator='operator_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListOperatorsRequest, + dict, +]) +def test_list_operators(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListOperatorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.ListOperatorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOperatorsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_operators_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 = LiveVideoAnalyticsClient( + 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_operators), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_operators() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListOperatorsRequest() + + +def test_list_operators_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.ListOperatorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_operators(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListOperatorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_operators_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_operators in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_operators] = mock_rpc + request = {} + client.list_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_operators(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_operators_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListOperatorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_operators() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListOperatorsRequest() + +@pytest.mark.asyncio +async def test_list_operators_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_operators in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_operators] = mock_object + + request = {} + await client.list_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_operators(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_operators_async(transport: str = 'grpc_asyncio', request_type=lva_service.ListOperatorsRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListOperatorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.ListOperatorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOperatorsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_operators_async_from_dict(): + await test_list_operators_async(request_type=dict) + + +def test_list_operators_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListOperatorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + call.return_value = lva_service.ListOperatorsResponse() + client.list_operators(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_operators_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListOperatorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListOperatorsResponse()) + await client.list_operators(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_operators_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListOperatorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_operators( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_operators_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_operators( + lva_service.ListOperatorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_operators_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListOperatorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListOperatorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_operators( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_operators_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_operators( + lva_service.ListOperatorsRequest(), + parent='parent_value', + ) + + +def test_list_operators_pager(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_operators(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Operator) + for i in results) +def test_list_operators_pages(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + pages = list(client.list_operators(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_operators_async_pager(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_operators(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, lva_resources.Operator) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_operators_async_pages(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_operators), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_operators(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + lva_service.GetOperatorRequest, + dict, +]) +def test_get_operator(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Operator( + name='name_value', + docker_image='docker_image_value', + ) + response = client.get_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.GetOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Operator) + assert response.name == 'name_value' + assert response.docker_image == 'docker_image_value' + + +def test_get_operator_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 = LiveVideoAnalyticsClient( + 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_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetOperatorRequest() + + +def test_get_operator_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.GetOperatorRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_operator(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetOperatorRequest( + name='name_value', + ) + +def test_get_operator_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_operator] = mock_rpc + request = {} + client.get_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_operator_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Operator( + name='name_value', + docker_image='docker_image_value', + )) + response = await client.get_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetOperatorRequest() + +@pytest.mark.asyncio +async def test_get_operator_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_operator in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_operator] = mock_object + + request = {} + await client.get_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_operator_async(transport: str = 'grpc_asyncio', request_type=lva_service.GetOperatorRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Operator( + name='name_value', + docker_image='docker_image_value', + )) + response = await client.get_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.GetOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Operator) + assert response.name == 'name_value' + assert response.docker_image == 'docker_image_value' + + +@pytest.mark.asyncio +async def test_get_operator_async_from_dict(): + await test_get_operator_async(request_type=dict) + + +def test_get_operator_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetOperatorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_operator), + '__call__') as call: + call.return_value = lva_resources.Operator() + client.get_operator(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_operator_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetOperatorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_operator), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Operator()) + await client.get_operator(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_operator_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Operator() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_operator( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_operator_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_operator( + lva_service.GetOperatorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_operator_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Operator() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Operator()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_operator( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_operator_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_operator( + lva_service.GetOperatorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateOperatorRequest, + dict, +]) +def test_create_operator(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.CreateOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_operator_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 = LiveVideoAnalyticsClient( + 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_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateOperatorRequest() + + +def test_create_operator_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.CreateOperatorRequest( + parent='parent_value', + operator_id='operator_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_operator(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateOperatorRequest( + parent='parent_value', + operator_id='operator_id_value', + request_id='request_id_value', + ) + +def test_create_operator_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_operator] = mock_rpc + request = {} + client.create_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_operator_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateOperatorRequest() + +@pytest.mark.asyncio +async def test_create_operator_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_operator in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_operator] = mock_object + + request = {} + await client.create_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_operator_async(transport: str = 'grpc_asyncio', request_type=lva_service.CreateOperatorRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.CreateOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_operator_async_from_dict(): + await test_create_operator_async(request_type=dict) + + +def test_create_operator_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateOperatorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_operator), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_operator(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_operator_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateOperatorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_operator), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_operator(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_operator_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_operator( + parent='parent_value', + operator=lva_resources.Operator(name='name_value'), + operator_id='operator_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].operator + mock_val = lva_resources.Operator(name='name_value') + assert arg == mock_val + arg = args[0].operator_id + mock_val = 'operator_id_value' + assert arg == mock_val + + +def test_create_operator_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_operator( + lva_service.CreateOperatorRequest(), + parent='parent_value', + operator=lva_resources.Operator(name='name_value'), + operator_id='operator_id_value', + ) + +@pytest.mark.asyncio +async def test_create_operator_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_operator( + parent='parent_value', + operator=lva_resources.Operator(name='name_value'), + operator_id='operator_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].operator + mock_val = lva_resources.Operator(name='name_value') + assert arg == mock_val + arg = args[0].operator_id + mock_val = 'operator_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_operator_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_operator( + lva_service.CreateOperatorRequest(), + parent='parent_value', + operator=lva_resources.Operator(name='name_value'), + operator_id='operator_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateOperatorRequest, + dict, +]) +def test_update_operator(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_operator_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 = LiveVideoAnalyticsClient( + 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_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateOperatorRequest() + + +def test_update_operator_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.UpdateOperatorRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_operator(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateOperatorRequest( + request_id='request_id_value', + ) + +def test_update_operator_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_operator] = mock_rpc + request = {} + client.update_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_operator_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateOperatorRequest() + +@pytest.mark.asyncio +async def test_update_operator_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_operator in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_operator] = mock_object + + request = {} + await client.update_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_operator_async(transport: str = 'grpc_asyncio', request_type=lva_service.UpdateOperatorRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_operator_async_from_dict(): + await test_update_operator_async(request_type=dict) + + +def test_update_operator_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateOperatorRequest() + + request.operator.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_operator), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_operator(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', + 'operator.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_operator_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateOperatorRequest() + + request.operator.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_operator), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_operator(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', + 'operator.name=name_value', + ) in kw['metadata'] + + +def test_update_operator_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_operator( + operator=lva_resources.Operator(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].operator + mock_val = lva_resources.Operator(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_operator_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_operator( + lva_service.UpdateOperatorRequest(), + operator=lva_resources.Operator(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_operator_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_operator( + operator=lva_resources.Operator(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].operator + mock_val = lva_resources.Operator(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_operator_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_operator( + lva_service.UpdateOperatorRequest(), + operator=lva_resources.Operator(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteOperatorRequest, + dict, +]) +def test_delete_operator(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_operator_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 = LiveVideoAnalyticsClient( + 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_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteOperatorRequest() + + +def test_delete_operator_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.DeleteOperatorRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_operator), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_operator(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteOperatorRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_operator_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_operator] = mock_rpc + request = {} + client.delete_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_operator_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_operator() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteOperatorRequest() + +@pytest.mark.asyncio +async def test_delete_operator_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_operator in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_operator] = mock_object + + request = {} + await client.delete_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_operator_async(transport: str = 'grpc_asyncio', request_type=lva_service.DeleteOperatorRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteOperatorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_operator_async_from_dict(): + await test_delete_operator_async(request_type=dict) + + +def test_delete_operator_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteOperatorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_operator), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_operator(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_operator_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteOperatorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_operator), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_operator(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_operator_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_operator( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_operator_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_operator( + lva_service.DeleteOperatorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_operator_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_operator), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_operator( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_operator_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_operator( + lva_service.DeleteOperatorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListAnalysesRequest, + dict, +]) +def test_list_analyses(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.ListAnalysesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnalysesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_analyses_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 = LiveVideoAnalyticsClient( + 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_analyses), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_analyses() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListAnalysesRequest() + + +def test_list_analyses_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.ListAnalysesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_analyses(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListAnalysesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_analyses_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_analyses in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_analyses] = mock_rpc + request = {} + client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_analyses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_analyses_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_analyses() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListAnalysesRequest() + +@pytest.mark.asyncio +async def test_list_analyses_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_analyses in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_analyses] = mock_object + + request = {} + await client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_analyses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_analyses_async(transport: str = 'grpc_asyncio', request_type=lva_service.ListAnalysesRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.ListAnalysesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnalysesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_analyses_async_from_dict(): + await test_list_analyses_async(request_type=dict) + + +def test_list_analyses_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListAnalysesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + call.return_value = lva_service.ListAnalysesResponse() + client.list_analyses(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_analyses_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListAnalysesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse()) + await client.list_analyses(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_analyses_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListAnalysesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_analyses( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_analyses_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analyses( + lva_service.ListAnalysesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_analyses_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListAnalysesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_analyses( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_analyses_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analyses( + lva_service.ListAnalysesRequest(), + parent='parent_value', + ) + + +def test_list_analyses_pager(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_analyses(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Analysis) + for i in results) +def test_list_analyses_pages(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + pages = list(client.list_analyses(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_analyses_async_pager(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_analyses(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, lva_resources.Analysis) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_analyses_async_pages(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_analyses(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + lva_service.GetAnalysisRequest, + dict, +]) +def test_get_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Analysis( + name='name_value', + disable_event_watch=True, + ) + response = client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.GetAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Analysis) + assert response.name == 'name_value' + assert response.disable_event_watch is True + + +def test_get_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetAnalysisRequest() + + +def test_get_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.GetAnalysisRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetAnalysisRequest( + name='name_value', + ) + +def test_get_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_analysis] = mock_rpc + request = {} + client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis( + name='name_value', + disable_event_watch=True, + )) + response = await client.get_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetAnalysisRequest() + +@pytest.mark.asyncio +async def test_get_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_analysis] = mock_object + + request = {} + await client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.GetAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis( + name='name_value', + disable_event_watch=True, + )) + response = await client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.GetAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Analysis) + assert response.name == 'name_value' + assert response.disable_event_watch is True + + +@pytest.mark.asyncio +async def test_get_analysis_async_from_dict(): + await test_get_analysis_async(request_type=dict) + + +def test_get_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + call.return_value = lva_resources.Analysis() + client.get_analysis(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_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis()) + await client.get_analysis(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_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Analysis() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.GetAnalysisRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Analysis() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.GetAnalysisRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateAnalysisRequest, + dict, +]) +def test_create_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.CreateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateAnalysisRequest() + + +def test_create_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.CreateAnalysisRequest( + parent='parent_value', + analysis_id='analysis_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateAnalysisRequest( + parent='parent_value', + analysis_id='analysis_id_value', + request_id='request_id_value', + ) + +def test_create_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_analysis] = mock_rpc + request = {} + client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateAnalysisRequest() + +@pytest.mark.asyncio +async def test_create_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_analysis] = mock_object + + request = {} + await client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.CreateAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.CreateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_analysis_async_from_dict(): + await test_create_analysis_async(request_type=dict) + + +def test_create_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateAnalysisRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_analysis(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_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateAnalysisRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_analysis(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_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_analysis( + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].analysis_id + mock_val = 'analysis_id_value' + assert arg == mock_val + + +def test_create_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.CreateAnalysisRequest(), + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + +@pytest.mark.asyncio +async def test_create_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_analysis( + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].analysis_id + mock_val = 'analysis_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.CreateAnalysisRequest(), + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateAnalysisRequest, + dict, +]) +def test_update_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateAnalysisRequest() + + +def test_update_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.UpdateAnalysisRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateAnalysisRequest( + request_id='request_id_value', + ) + +def test_update_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_analysis] = mock_rpc + request = {} + client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateAnalysisRequest() + +@pytest.mark.asyncio +async def test_update_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_analysis] = mock_object + + request = {} + await client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.UpdateAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_analysis_async_from_dict(): + await test_update_analysis_async(request_type=dict) + + +def test_update_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateAnalysisRequest() + + request.analysis.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_analysis(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', + 'analysis.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateAnalysisRequest() + + request.analysis.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_analysis(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', + 'analysis.name=name_value', + ) in kw['metadata'] + + +def test_update_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_analysis( + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.UpdateAnalysisRequest(), + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_analysis( + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.UpdateAnalysisRequest(), + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteAnalysisRequest, + dict, +]) +def test_delete_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteAnalysisRequest() + + +def test_delete_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.DeleteAnalysisRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteAnalysisRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_analysis] = mock_rpc + request = {} + client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteAnalysisRequest() + +@pytest.mark.asyncio +async def test_delete_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_analysis] = mock_object + + request = {} + await client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.DeleteAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_analysis_async_from_dict(): + await test_delete_analysis_async(request_type=dict) + + +def test_delete_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_analysis(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_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_analysis(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_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.DeleteAnalysisRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.DeleteAnalysisRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListProcessesRequest, + dict, +]) +def test_list_processes(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListProcessesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_processes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.ListProcessesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_processes_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 = LiveVideoAnalyticsClient( + 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_processes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_processes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListProcessesRequest() + + +def test_list_processes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.ListProcessesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_processes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListProcessesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_processes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_processes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_processes] = mock_rpc + request = {} + client.list_processes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_processes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_processes_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListProcessesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_processes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListProcessesRequest() + +@pytest.mark.asyncio +async def test_list_processes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_processes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_processes] = mock_object + + request = {} + await client.list_processes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_processes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_processes_async(transport: str = 'grpc_asyncio', request_type=lva_service.ListProcessesRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListProcessesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_processes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.ListProcessesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_processes_async_from_dict(): + await test_list_processes_async(request_type=dict) + + +def test_list_processes_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListProcessesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + call.return_value = lva_service.ListProcessesResponse() + client.list_processes(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_processes_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListProcessesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListProcessesResponse()) + await client.list_processes(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_processes_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListProcessesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processes( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_processes_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_processes( + lva_service.ListProcessesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processes_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListProcessesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListProcessesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processes( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_processes_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_processes( + lva_service.ListProcessesRequest(), + parent='parent_value', + ) + + +def test_list_processes_pager(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + lva_resources.Process(), + ], + next_page_token='abc', + ), + lva_service.ListProcessesResponse( + processes=[], + next_page_token='def', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + ], + next_page_token='ghi', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processes(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Process) + for i in results) +def test_list_processes_pages(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + lva_resources.Process(), + ], + next_page_token='abc', + ), + lva_service.ListProcessesResponse( + processes=[], + next_page_token='def', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + ], + next_page_token='ghi', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processes(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_processes_async_pager(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + lva_resources.Process(), + ], + next_page_token='abc', + ), + lva_service.ListProcessesResponse( + processes=[], + next_page_token='def', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + ], + next_page_token='ghi', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processes(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, lva_resources.Process) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processes_async_pages(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + lva_resources.Process(), + ], + next_page_token='abc', + ), + lva_service.ListProcessesResponse( + processes=[], + next_page_token='def', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + ], + next_page_token='ghi', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_processes(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + lva_service.GetProcessRequest, + dict, +]) +def test_get_process(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Process( + name='name_value', + analysis='analysis_value', + attribute_overrides=['attribute_overrides_value'], + run_mode=lva.RunMode.LIVE, + event_id='event_id_value', + batch_id='batch_id_value', + retry_count=1214, + ) + response = client.get_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.GetProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Process) + assert response.name == 'name_value' + assert response.analysis == 'analysis_value' + assert response.attribute_overrides == ['attribute_overrides_value'] + assert response.run_mode == lva.RunMode.LIVE + assert response.event_id == 'event_id_value' + assert response.batch_id == 'batch_id_value' + assert response.retry_count == 1214 + + +def test_get_process_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 = LiveVideoAnalyticsClient( + 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_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetProcessRequest() + + +def test_get_process_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.GetProcessRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_process(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetProcessRequest( + name='name_value', + ) + +def test_get_process_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_process] = mock_rpc + request = {} + client.get_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_process_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Process( + name='name_value', + analysis='analysis_value', + attribute_overrides=['attribute_overrides_value'], + run_mode=lva.RunMode.LIVE, + event_id='event_id_value', + batch_id='batch_id_value', + retry_count=1214, + )) + response = await client.get_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetProcessRequest() + +@pytest.mark.asyncio +async def test_get_process_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_process in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_process] = mock_object + + request = {} + await client.get_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_process_async(transport: str = 'grpc_asyncio', request_type=lva_service.GetProcessRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Process( + name='name_value', + analysis='analysis_value', + attribute_overrides=['attribute_overrides_value'], + run_mode=lva.RunMode.LIVE, + event_id='event_id_value', + batch_id='batch_id_value', + retry_count=1214, + )) + response = await client.get_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.GetProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Process) + assert response.name == 'name_value' + assert response.analysis == 'analysis_value' + assert response.attribute_overrides == ['attribute_overrides_value'] + assert response.run_mode == lva.RunMode.LIVE + assert response.event_id == 'event_id_value' + assert response.batch_id == 'batch_id_value' + assert response.retry_count == 1214 + + +@pytest.mark.asyncio +async def test_get_process_async_from_dict(): + await test_get_process_async(request_type=dict) + + +def test_get_process_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_process), + '__call__') as call: + call.return_value = lva_resources.Process() + client.get_process(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_process_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_process), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Process()) + await client.get_process(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_process_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Process() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_process( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_process_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_process( + lva_service.GetProcessRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_process_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Process() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Process()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_process( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_process_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_process( + lva_service.GetProcessRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateProcessRequest, + dict, +]) +def test_create_process(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.CreateProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_process_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 = LiveVideoAnalyticsClient( + 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_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateProcessRequest() + + +def test_create_process_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.CreateProcessRequest( + parent='parent_value', + process_id='process_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_process(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateProcessRequest( + parent='parent_value', + process_id='process_id_value', + request_id='request_id_value', + ) + +def test_create_process_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_process] = mock_rpc + request = {} + client.create_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_process_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateProcessRequest() + +@pytest.mark.asyncio +async def test_create_process_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_process in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_process] = mock_object + + request = {} + await client.create_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_process_async(transport: str = 'grpc_asyncio', request_type=lva_service.CreateProcessRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.CreateProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_process_async_from_dict(): + await test_create_process_async(request_type=dict) + + +def test_create_process_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateProcessRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_process), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_process(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_process_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateProcessRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_process), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_process(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_process_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_process( + parent='parent_value', + process=lva_resources.Process(name='name_value'), + process_id='process_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].process + mock_val = lva_resources.Process(name='name_value') + assert arg == mock_val + arg = args[0].process_id + mock_val = 'process_id_value' + assert arg == mock_val + + +def test_create_process_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_process( + lva_service.CreateProcessRequest(), + parent='parent_value', + process=lva_resources.Process(name='name_value'), + process_id='process_id_value', + ) + +@pytest.mark.asyncio +async def test_create_process_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_process( + parent='parent_value', + process=lva_resources.Process(name='name_value'), + process_id='process_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].process + mock_val = lva_resources.Process(name='name_value') + assert arg == mock_val + arg = args[0].process_id + mock_val = 'process_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_process_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_process( + lva_service.CreateProcessRequest(), + parent='parent_value', + process=lva_resources.Process(name='name_value'), + process_id='process_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateProcessRequest, + dict, +]) +def test_update_process(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_process_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 = LiveVideoAnalyticsClient( + 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_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateProcessRequest() + + +def test_update_process_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.UpdateProcessRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_process(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateProcessRequest( + request_id='request_id_value', + ) + +def test_update_process_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_process] = mock_rpc + request = {} + client.update_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_process_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateProcessRequest() + +@pytest.mark.asyncio +async def test_update_process_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_process in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_process] = mock_object + + request = {} + await client.update_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_process_async(transport: str = 'grpc_asyncio', request_type=lva_service.UpdateProcessRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_process_async_from_dict(): + await test_update_process_async(request_type=dict) + + +def test_update_process_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateProcessRequest() + + request.process.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_process), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_process(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', + 'process.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_process_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateProcessRequest() + + request.process.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_process), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_process(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', + 'process.name=name_value', + ) in kw['metadata'] + + +def test_update_process_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_process( + process=lva_resources.Process(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].process + mock_val = lva_resources.Process(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_process_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_process( + lva_service.UpdateProcessRequest(), + process=lva_resources.Process(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_process_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_process( + process=lva_resources.Process(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].process + mock_val = lva_resources.Process(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_process_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_process( + lva_service.UpdateProcessRequest(), + process=lva_resources.Process(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteProcessRequest, + dict, +]) +def test_delete_process(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_process_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 = LiveVideoAnalyticsClient( + 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_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteProcessRequest() + + +def test_delete_process_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.DeleteProcessRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_process(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteProcessRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_process_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_process] = mock_rpc + request = {} + client.delete_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_process_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteProcessRequest() + +@pytest.mark.asyncio +async def test_delete_process_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_process in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_process] = mock_object + + request = {} + await client.delete_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_process_async(transport: str = 'grpc_asyncio', request_type=lva_service.DeleteProcessRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_process_async_from_dict(): + await test_delete_process_async(request_type=dict) + + +def test_delete_process_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_process), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_process(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_process_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteProcessRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_process), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_process(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_process_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_process( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_process_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_process( + lva_service.DeleteProcessRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_process_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_process( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_process_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_process( + lva_service.DeleteProcessRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.BatchRunProcessRequest, + dict, +]) +def test_batch_run_process(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_run_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_run_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.BatchRunProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_run_process_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 = LiveVideoAnalyticsClient( + 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_run_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_run_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.BatchRunProcessRequest() + + +def test_batch_run_process_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.BatchRunProcessRequest( + parent='parent_value', + batch_id='batch_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_process), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_run_process(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.BatchRunProcessRequest( + parent='parent_value', + batch_id='batch_id_value', + ) + +def test_batch_run_process_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_run_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_run_process] = mock_rpc + request = {} + client.batch_run_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_run_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_run_process_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_run_process() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.BatchRunProcessRequest() + +@pytest.mark.asyncio +async def test_batch_run_process_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.batch_run_process in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.batch_run_process] = mock_object + + request = {} + await client.batch_run_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.batch_run_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_run_process_async(transport: str = 'grpc_asyncio', request_type=lva_service.BatchRunProcessRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_run_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_run_process(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.BatchRunProcessRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_run_process_async_from_dict(): + await test_batch_run_process_async(request_type=dict) + + +def test_batch_run_process_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.BatchRunProcessRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_process), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_run_process(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_run_process_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.BatchRunProcessRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_process), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_run_process(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_run_process_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_run_process( + parent='parent_value', + requests=[lva_service.CreateProcessRequest(parent='parent_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].requests + mock_val = [lva_service.CreateProcessRequest(parent='parent_value')] + assert arg == mock_val + + +def test_batch_run_process_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_run_process( + lva_service.BatchRunProcessRequest(), + parent='parent_value', + requests=[lva_service.CreateProcessRequest(parent='parent_value')], + ) + +@pytest.mark.asyncio +async def test_batch_run_process_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_process), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_run_process( + parent='parent_value', + requests=[lva_service.CreateProcessRequest(parent='parent_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].requests + mock_val = [lva_service.CreateProcessRequest(parent='parent_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_run_process_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_run_process( + lva_service.BatchRunProcessRequest(), + parent='parent_value', + requests=[lva_service.CreateProcessRequest(parent='parent_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListPublicOperatorsRequest, + dict, +]) +def test_list_public_operators_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListPublicOperatorsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListPublicOperatorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_public_operators(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPublicOperatorsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_public_operators_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_public_operators in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_public_operators] = mock_rpc + + request = {} + client.list_public_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_public_operators(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_public_operators_rest_required_fields(request_type=lva_service.ListPublicOperatorsRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_public_operators._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_public_operators._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_service.ListPublicOperatorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_service.ListPublicOperatorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_public_operators(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_public_operators_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_public_operators._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_public_operators_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_list_public_operators") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_list_public_operators") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.ListPublicOperatorsRequest.pb(lva_service.ListPublicOperatorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_service.ListPublicOperatorsResponse.to_json(lva_service.ListPublicOperatorsResponse()) + + request = lva_service.ListPublicOperatorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_service.ListPublicOperatorsResponse() + + client.list_public_operators(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_public_operators_rest_bad_request(transport: str = 'rest', request_type=lva_service.ListPublicOperatorsRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_public_operators(request) + + +def test_list_public_operators_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListPublicOperatorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListPublicOperatorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_public_operators(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}:listPublicOperators" % client.transport._host, args[1]) + + +def test_list_public_operators_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_public_operators( + lva_service.ListPublicOperatorsRequest(), + parent='parent_value', + ) + + +def test_list_public_operators_rest_pager(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListPublicOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListPublicOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lva_service.ListPublicOperatorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_public_operators(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Operator) + for i in results) + + pages = list(client.list_public_operators(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + lva_service.ResolveOperatorInfoRequest, + dict, +]) +def test_resolve_operator_info_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ResolveOperatorInfoResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ResolveOperatorInfoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.resolve_operator_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_service.ResolveOperatorInfoResponse) + +def test_resolve_operator_info_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.resolve_operator_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.resolve_operator_info] = mock_rpc + + request = {} + client.resolve_operator_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.resolve_operator_info(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_resolve_operator_info_rest_required_fields(request_type=lva_service.ResolveOperatorInfoRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).resolve_operator_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).resolve_operator_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_service.ResolveOperatorInfoResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_service.ResolveOperatorInfoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.resolve_operator_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_resolve_operator_info_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.resolve_operator_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "queries", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resolve_operator_info_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_resolve_operator_info") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_resolve_operator_info") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.ResolveOperatorInfoRequest.pb(lva_service.ResolveOperatorInfoRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_service.ResolveOperatorInfoResponse.to_json(lva_service.ResolveOperatorInfoResponse()) + + request = lva_service.ResolveOperatorInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_service.ResolveOperatorInfoResponse() + + client.resolve_operator_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_resolve_operator_info_rest_bad_request(transport: str = 'rest', request_type=lva_service.ResolveOperatorInfoRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.resolve_operator_info(request) + + +def test_resolve_operator_info_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ResolveOperatorInfoResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + queries=[lva_service.OperatorQuery(operator='operator_value')], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ResolveOperatorInfoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.resolve_operator_info(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}:resolveOperatorInfo" % client.transport._host, args[1]) + + +def test_resolve_operator_info_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.resolve_operator_info( + lva_service.ResolveOperatorInfoRequest(), + parent='parent_value', + queries=[lva_service.OperatorQuery(operator='operator_value')], + ) + + +def test_resolve_operator_info_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListOperatorsRequest, + dict, +]) +def test_list_operators_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListOperatorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListOperatorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_operators(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOperatorsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_operators_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_operators in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_operators] = mock_rpc + + request = {} + client.list_operators(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_operators(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_operators_rest_required_fields(request_type=lva_service.ListOperatorsRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_operators._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_operators._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_service.ListOperatorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_service.ListOperatorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operators(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_operators_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_operators._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_operators_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_list_operators") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_list_operators") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.ListOperatorsRequest.pb(lva_service.ListOperatorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_service.ListOperatorsResponse.to_json(lva_service.ListOperatorsResponse()) + + request = lva_service.ListOperatorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_service.ListOperatorsResponse() + + client.list_operators(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_operators_rest_bad_request(transport: str = 'rest', request_type=lva_service.ListOperatorsRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operators(request) + + +def test_list_operators_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListOperatorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListOperatorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_operators(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/operators" % client.transport._host, args[1]) + + +def test_list_operators_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_operators( + lva_service.ListOperatorsRequest(), + parent='parent_value', + ) + + +def test_list_operators_rest_pager(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + lva_resources.Operator(), + ], + next_page_token='abc', + ), + lva_service.ListOperatorsResponse( + operators=[], + next_page_token='def', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + ], + next_page_token='ghi', + ), + lva_service.ListOperatorsResponse( + operators=[ + lva_resources.Operator(), + lva_resources.Operator(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lva_service.ListOperatorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_operators(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Operator) + for i in results) + + pages = list(client.list_operators(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + lva_service.GetOperatorRequest, + dict, +]) +def test_get_operator_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/operators/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Operator( + name='name_value', + docker_image='docker_image_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Operator.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_operator(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Operator) + assert response.name == 'name_value' + assert response.docker_image == 'docker_image_value' + +def test_get_operator_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_operator] = mock_rpc + + request = {} + client.get_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_operator_rest_required_fields(request_type=lva_service.GetOperatorRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_operator._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_operator._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_resources.Operator() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_resources.Operator.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operator(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_operator_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_operator._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_operator_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_get_operator") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_get_operator") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.GetOperatorRequest.pb(lva_service.GetOperatorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_resources.Operator.to_json(lva_resources.Operator()) + + request = lva_service.GetOperatorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_resources.Operator() + + client.get_operator(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operator_rest_bad_request(transport: str = 'rest', request_type=lva_service.GetOperatorRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/operators/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operator(request) + + +def test_get_operator_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Operator() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/operators/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Operator.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_operator(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/operators/*}" % client.transport._host, args[1]) + + +def test_get_operator_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_operator( + lva_service.GetOperatorRequest(), + name='name_value', + ) + + +def test_get_operator_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateOperatorRequest, + dict, +]) +def test_create_operator_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["operator"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'operator_definition': {'operator': 'operator_value', 'input_args': [{'argument': 'argument_value', 'type_': 'type__value'}], 'output_args': {}, 'attributes': [{'attribute': 'attribute_value', 'type_': 'type__value', 'default_value': {'i': 105, 'f': 0.10200000000000001, 'b': True, 's': b's_blob'}}], 'resources': {'cpu': 'cpu_value', 'cpu_limits': 'cpu_limits_value', 'memory': 'memory_value', 'memory_limits': 'memory_limits_value', 'gpus': 447, 'latency_budget_ms': 1801}, 'short_description': 'short_description_value', 'description': 'description_value'}, 'docker_image': 'docker_image_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.CreateOperatorRequest.meta.fields["operator"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["operator"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["operator"][field])): + del request_init["operator"][field][i][subfield] + else: + del request_init["operator"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_operator(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_operator_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_operator] = mock_rpc + + request = {} + client.create_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_operator_rest_required_fields(request_type=lva_service.CreateOperatorRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["operator_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "operatorId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_operator._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "operatorId" in jsonified_request + assert jsonified_request["operatorId"] == request_init["operator_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["operatorId"] = 'operator_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_operator._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("operator_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "operatorId" in jsonified_request + assert jsonified_request["operatorId"] == 'operator_id_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_operator(request) + + expected_params = [ + ( + "operatorId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_operator_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_operator._get_unset_required_fields({}) + assert set(unset_fields) == (set(("operatorId", "requestId", )) & set(("parent", "operatorId", "operator", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_operator_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_create_operator") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_create_operator") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.CreateOperatorRequest.pb(lva_service.CreateOperatorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.CreateOperatorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_operator(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_operator_rest_bad_request(transport: str = 'rest', request_type=lva_service.CreateOperatorRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_operator(request) + + +def test_create_operator_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + operator=lva_resources.Operator(name='name_value'), + operator_id='operator_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_operator(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/operators" % client.transport._host, args[1]) + + +def test_create_operator_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_operator( + lva_service.CreateOperatorRequest(), + parent='parent_value', + operator=lva_resources.Operator(name='name_value'), + operator_id='operator_id_value', + ) + + +def test_create_operator_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateOperatorRequest, + dict, +]) +def test_update_operator_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'operator': {'name': 'projects/sample1/locations/sample2/operators/sample3'}} + request_init["operator"] = {'name': 'projects/sample1/locations/sample2/operators/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'operator_definition': {'operator': 'operator_value', 'input_args': [{'argument': 'argument_value', 'type_': 'type__value'}], 'output_args': {}, 'attributes': [{'attribute': 'attribute_value', 'type_': 'type__value', 'default_value': {'i': 105, 'f': 0.10200000000000001, 'b': True, 's': b's_blob'}}], 'resources': {'cpu': 'cpu_value', 'cpu_limits': 'cpu_limits_value', 'memory': 'memory_value', 'memory_limits': 'memory_limits_value', 'gpus': 447, 'latency_budget_ms': 1801}, 'short_description': 'short_description_value', 'description': 'description_value'}, 'docker_image': 'docker_image_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.UpdateOperatorRequest.meta.fields["operator"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["operator"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["operator"][field])): + del request_init["operator"][field][i][subfield] + else: + del request_init["operator"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_operator(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_operator_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_operator] = mock_rpc + + request = {} + client.update_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_operator_rest_required_fields(request_type=lva_service.UpdateOperatorRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_operator._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_operator._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_operator(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_operator_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_operator._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "operator", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_operator_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_update_operator") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_update_operator") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.UpdateOperatorRequest.pb(lva_service.UpdateOperatorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.UpdateOperatorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_operator(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_operator_rest_bad_request(transport: str = 'rest', request_type=lva_service.UpdateOperatorRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'operator': {'name': 'projects/sample1/locations/sample2/operators/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_operator(request) + + +def test_update_operator_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'operator': {'name': 'projects/sample1/locations/sample2/operators/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + operator=lva_resources.Operator(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_operator(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{operator.name=projects/*/locations/*/operators/*}" % client.transport._host, args[1]) + + +def test_update_operator_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_operator( + lva_service.UpdateOperatorRequest(), + operator=lva_resources.Operator(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_operator_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteOperatorRequest, + dict, +]) +def test_delete_operator_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/operators/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_operator(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_operator_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_operator in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_operator] = mock_rpc + + request = {} + client.delete_operator(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_operator(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_operator_rest_required_fields(request_type=lva_service.DeleteOperatorRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_operator._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_operator._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operator(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_operator_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_operator._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_operator_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_delete_operator") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_delete_operator") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.DeleteOperatorRequest.pb(lva_service.DeleteOperatorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.DeleteOperatorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_operator(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_operator_rest_bad_request(transport: str = 'rest', request_type=lva_service.DeleteOperatorRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/operators/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operator(request) + + +def test_delete_operator_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/operators/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_operator(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/operators/*}" % client.transport._host, args[1]) + + +def test_delete_operator_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_operator( + lva_service.DeleteOperatorRequest(), + name='name_value', + ) + + +def test_delete_operator_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListAnalysesRequest, + dict, +]) +def test_list_analyses_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListAnalysesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_analyses(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnalysesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_analyses_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_analyses in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_analyses] = mock_rpc + + request = {} + client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_analyses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_analyses_rest_required_fields(request_type=lva_service.ListAnalysesRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_analyses._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_analyses._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_service.ListAnalysesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_service.ListAnalysesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_analyses(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_analyses_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_analyses._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_analyses_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_list_analyses") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_list_analyses") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.ListAnalysesRequest.pb(lva_service.ListAnalysesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_service.ListAnalysesResponse.to_json(lva_service.ListAnalysesResponse()) + + request = lva_service.ListAnalysesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_service.ListAnalysesResponse() + + client.list_analyses(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_analyses_rest_bad_request(transport: str = 'rest', request_type=lva_service.ListAnalysesRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_analyses(request) + + +def test_list_analyses_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListAnalysesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListAnalysesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_analyses(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/analyses" % client.transport._host, args[1]) + + +def test_list_analyses_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_analyses( + lva_service.ListAnalysesRequest(), + parent='parent_value', + ) + + +def test_list_analyses_rest_pager(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lva_service.ListAnalysesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_analyses(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Analysis) + for i in results) + + pages = list(client.list_analyses(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + lva_service.GetAnalysisRequest, + dict, +]) +def test_get_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Analysis( + name='name_value', + disable_event_watch=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Analysis.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_analysis(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Analysis) + assert response.name == 'name_value' + assert response.disable_event_watch is True + +def test_get_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_analysis] = mock_rpc + + request = {} + client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_analysis_rest_required_fields(request_type=lva_service.GetAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_resources.Analysis() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_resources.Analysis.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_analysis(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_get_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_get_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.GetAnalysisRequest.pb(lva_service.GetAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_resources.Analysis.to_json(lva_resources.Analysis()) + + request = lva_service.GetAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_resources.Analysis() + + client.get_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.GetAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_analysis(request) + + +def test_get_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Analysis() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Analysis.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/analyses/*}" % client.transport._host, args[1]) + + +def test_get_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_analysis( + lva_service.GetAnalysisRequest(), + name='name_value', + ) + + +def test_get_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateAnalysisRequest, + dict, +]) +def test_create_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["analysis"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'analysis_definition': {'analyzers': [{'analyzer': 'analyzer_value', 'operator': 'operator_value', 'inputs': [{'input': 'input_value'}], 'attrs': {}, 'debug_options': {'environment_variables': {}}, 'operator_option': {'tag': 'tag_value', 'registry': 'registry_value'}}]}, 'input_streams_mapping': {}, 'output_streams_mapping': {}, 'disable_event_watch': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.CreateAnalysisRequest.meta.fields["analysis"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["analysis"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["analysis"][field])): + del request_init["analysis"][field][i][subfield] + else: + del request_init["analysis"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_analysis(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_analysis] = mock_rpc + + request = {} + client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_analysis_rest_required_fields(request_type=lva_service.CreateAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["analysis_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "analysisId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "analysisId" in jsonified_request + assert jsonified_request["analysisId"] == request_init["analysis_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["analysisId"] = 'analysis_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_analysis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("analysis_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "analysisId" in jsonified_request + assert jsonified_request["analysisId"] == 'analysis_id_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_analysis(request) + + expected_params = [ + ( + "analysisId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(("analysisId", "requestId", )) & set(("parent", "analysisId", "analysis", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_create_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_create_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.CreateAnalysisRequest.pb(lva_service.CreateAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.CreateAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.CreateAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_analysis(request) + + +def test_create_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/analyses" % client.transport._host, args[1]) + + +def test_create_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_analysis( + lva_service.CreateAnalysisRequest(), + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + +def test_create_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateAnalysisRequest, + dict, +]) +def test_update_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'analysis': {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'}} + request_init["analysis"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'analysis_definition': {'analyzers': [{'analyzer': 'analyzer_value', 'operator': 'operator_value', 'inputs': [{'input': 'input_value'}], 'attrs': {}, 'debug_options': {'environment_variables': {}}, 'operator_option': {'tag': 'tag_value', 'registry': 'registry_value'}}]}, 'input_streams_mapping': {}, 'output_streams_mapping': {}, 'disable_event_watch': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.UpdateAnalysisRequest.meta.fields["analysis"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["analysis"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["analysis"][field])): + del request_init["analysis"][field][i][subfield] + else: + del request_init["analysis"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_analysis(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_analysis] = mock_rpc + + request = {} + client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_analysis_rest_required_fields(request_type=lva_service.UpdateAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_analysis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_analysis(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "analysis", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_update_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_update_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.UpdateAnalysisRequest.pb(lva_service.UpdateAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.UpdateAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.UpdateAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'analysis': {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_analysis(request) + + +def test_update_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'analysis': {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{analysis.name=projects/*/locations/*/clusters/*/analyses/*}" % client.transport._host, args[1]) + + +def test_update_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_analysis( + lva_service.UpdateAnalysisRequest(), + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteAnalysisRequest, + dict, +]) +def test_delete_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_analysis(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_analysis] = mock_rpc + + request = {} + client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_analysis_rest_required_fields(request_type=lva_service.DeleteAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_analysis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_analysis(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_delete_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_delete_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.DeleteAnalysisRequest.pb(lva_service.DeleteAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.DeleteAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.DeleteAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_analysis(request) + + +def test_delete_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/analyses/*}" % client.transport._host, args[1]) + + +def test_delete_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_analysis( + lva_service.DeleteAnalysisRequest(), + name='name_value', + ) + + +def test_delete_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListProcessesRequest, + dict, +]) +def test_list_processes_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListProcessesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListProcessesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_processes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_processes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_processes] = mock_rpc + + request = {} + client.list_processes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_processes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_processes_rest_required_fields(request_type=lva_service.ListProcessesRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_service.ListProcessesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_service.ListProcessesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processes_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processes_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_list_processes") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_list_processes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.ListProcessesRequest.pb(lva_service.ListProcessesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_service.ListProcessesResponse.to_json(lva_service.ListProcessesResponse()) + + request = lva_service.ListProcessesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_service.ListProcessesResponse() + + client.list_processes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processes_rest_bad_request(transport: str = 'rest', request_type=lva_service.ListProcessesRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processes(request) + + +def test_list_processes_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListProcessesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListProcessesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/processes" % client.transport._host, args[1]) + + +def test_list_processes_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processes( + lva_service.ListProcessesRequest(), + parent='parent_value', + ) + + +def test_list_processes_rest_pager(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + lva_resources.Process(), + ], + next_page_token='abc', + ), + lva_service.ListProcessesResponse( + processes=[], + next_page_token='def', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + ], + next_page_token='ghi', + ), + lva_service.ListProcessesResponse( + processes=[ + lva_resources.Process(), + lva_resources.Process(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lva_service.ListProcessesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_processes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Process) + for i in results) + + pages = list(client.list_processes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + lva_service.GetProcessRequest, + dict, +]) +def test_get_process_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Process( + name='name_value', + analysis='analysis_value', + attribute_overrides=['attribute_overrides_value'], + run_mode=lva.RunMode.LIVE, + event_id='event_id_value', + batch_id='batch_id_value', + retry_count=1214, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Process.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_process(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Process) + assert response.name == 'name_value' + assert response.analysis == 'analysis_value' + assert response.attribute_overrides == ['attribute_overrides_value'] + assert response.run_mode == lva.RunMode.LIVE + assert response.event_id == 'event_id_value' + assert response.batch_id == 'batch_id_value' + assert response.retry_count == 1214 + +def test_get_process_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_process] = mock_rpc + + request = {} + client.get_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_process_rest_required_fields(request_type=lva_service.GetProcessRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_process._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_process._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_resources.Process() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_resources.Process.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_process(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_process_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_process._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_process_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_get_process") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_get_process") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.GetProcessRequest.pb(lva_service.GetProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_resources.Process.to_json(lva_resources.Process()) + + request = lva_service.GetProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_resources.Process() + + client.get_process(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_process_rest_bad_request(transport: str = 'rest', request_type=lva_service.GetProcessRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_process(request) + + +def test_get_process_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Process() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Process.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_process(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/processes/*}" % client.transport._host, args[1]) + + +def test_get_process_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_process( + lva_service.GetProcessRequest(), + name='name_value', + ) + + +def test_get_process_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateProcessRequest, + dict, +]) +def test_create_process_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["process"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'analysis': 'analysis_value', 'attribute_overrides': ['attribute_overrides_value1', 'attribute_overrides_value2'], 'run_status': {'state': 1, 'reason': 'reason_value'}, 'run_mode': 1, 'event_id': 'event_id_value', 'batch_id': 'batch_id_value', 'retry_count': 1214} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.CreateProcessRequest.meta.fields["process"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["process"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["process"][field])): + del request_init["process"][field][i][subfield] + else: + del request_init["process"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_process(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_process_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_process] = mock_rpc + + request = {} + client.create_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_process_rest_required_fields(request_type=lva_service.CreateProcessRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["process_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "processId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_process._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "processId" in jsonified_request + assert jsonified_request["processId"] == request_init["process_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["processId"] = 'process_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_process._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("process_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "processId" in jsonified_request + assert jsonified_request["processId"] == 'process_id_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_process(request) + + expected_params = [ + ( + "processId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_process_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_process._get_unset_required_fields({}) + assert set(unset_fields) == (set(("processId", "requestId", )) & set(("parent", "processId", "process", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_process_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_create_process") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_create_process") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.CreateProcessRequest.pb(lva_service.CreateProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.CreateProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_process(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_process_rest_bad_request(transport: str = 'rest', request_type=lva_service.CreateProcessRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_process(request) + + +def test_create_process_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + process=lva_resources.Process(name='name_value'), + process_id='process_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_process(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/processes" % client.transport._host, args[1]) + + +def test_create_process_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_process( + lva_service.CreateProcessRequest(), + parent='parent_value', + process=lva_resources.Process(name='name_value'), + process_id='process_id_value', + ) + + +def test_create_process_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateProcessRequest, + dict, +]) +def test_update_process_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'process': {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'}} + request_init["process"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'analysis': 'analysis_value', 'attribute_overrides': ['attribute_overrides_value1', 'attribute_overrides_value2'], 'run_status': {'state': 1, 'reason': 'reason_value'}, 'run_mode': 1, 'event_id': 'event_id_value', 'batch_id': 'batch_id_value', 'retry_count': 1214} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.UpdateProcessRequest.meta.fields["process"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["process"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["process"][field])): + del request_init["process"][field][i][subfield] + else: + del request_init["process"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_process(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_process_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_process] = mock_rpc + + request = {} + client.update_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_process_rest_required_fields(request_type=lva_service.UpdateProcessRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_process._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_process._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_process(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_process_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_process._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "process", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_process_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_update_process") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_update_process") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.UpdateProcessRequest.pb(lva_service.UpdateProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.UpdateProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_process(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_process_rest_bad_request(transport: str = 'rest', request_type=lva_service.UpdateProcessRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'process': {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_process(request) + + +def test_update_process_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'process': {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + process=lva_resources.Process(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_process(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{process.name=projects/*/locations/*/clusters/*/processes/*}" % client.transport._host, args[1]) + + +def test_update_process_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_process( + lva_service.UpdateProcessRequest(), + process=lva_resources.Process(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_process_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteProcessRequest, + dict, +]) +def test_delete_process_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_process(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_process_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_process] = mock_rpc + + request = {} + client.delete_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_process_rest_required_fields(request_type=lva_service.DeleteProcessRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_process._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_process._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_process(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_process_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_process._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_process_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_delete_process") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_delete_process") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.DeleteProcessRequest.pb(lva_service.DeleteProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.DeleteProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_process(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_process_rest_bad_request(transport: str = 'rest', request_type=lva_service.DeleteProcessRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_process(request) + + +def test_delete_process_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/processes/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_process(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/processes/*}" % client.transport._host, args[1]) + + +def test_delete_process_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_process( + lva_service.DeleteProcessRequest(), + name='name_value', + ) + + +def test_delete_process_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.BatchRunProcessRequest, + dict, +]) +def test_batch_run_process_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_run_process(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_batch_run_process_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_run_process in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_run_process] = mock_rpc + + request = {} + client.batch_run_process(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_run_process(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_run_process_rest_required_fields(request_type=lva_service.BatchRunProcessRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_run_process._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_run_process._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_run_process(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_run_process_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_run_process._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_run_process_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_batch_run_process") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_batch_run_process") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.BatchRunProcessRequest.pb(lva_service.BatchRunProcessRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.BatchRunProcessRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_run_process(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_run_process_rest_bad_request(transport: str = 'rest', request_type=lva_service.BatchRunProcessRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_run_process(request) + + +def test_batch_run_process_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + requests=[lva_service.CreateProcessRequest(parent='parent_value')], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.batch_run_process(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/processes:batchRun" % client.transport._host, args[1]) + + +def test_batch_run_process_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_run_process( + lva_service.BatchRunProcessRequest(), + parent='parent_value', + requests=[lva_service.CreateProcessRequest(parent='parent_value')], + ) + + +def test_batch_run_process_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LiveVideoAnalyticsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsGrpcAsyncIOTransport, + transports.LiveVideoAnalyticsRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = LiveVideoAnalyticsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LiveVideoAnalyticsGrpcTransport, + ) + +def test_live_video_analytics_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LiveVideoAnalyticsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_live_video_analytics_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1.services.live_video_analytics.transports.LiveVideoAnalyticsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LiveVideoAnalyticsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_public_operators', + 'resolve_operator_info', + 'list_operators', + 'get_operator', + 'create_operator', + 'update_operator', + 'delete_operator', + 'list_analyses', + 'get_analysis', + 'create_analysis', + 'update_analysis', + 'delete_analysis', + 'list_processes', + 'get_process', + 'create_process', + 'update_process', + 'delete_process', + 'batch_run_process', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_live_video_analytics_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1.services.live_video_analytics.transports.LiveVideoAnalyticsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LiveVideoAnalyticsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_live_video_analytics_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1.services.live_video_analytics.transports.LiveVideoAnalyticsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LiveVideoAnalyticsTransport() + adc.assert_called_once() + + +def test_live_video_analytics_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) + LiveVideoAnalyticsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsGrpcAsyncIOTransport, + ], +) +def test_live_video_analytics_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsGrpcAsyncIOTransport, + transports.LiveVideoAnalyticsRestTransport, + ], +) +def test_live_video_analytics_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LiveVideoAnalyticsGrpcTransport, grpc_helpers), + (transports.LiveVideoAnalyticsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_live_video_analytics_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( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LiveVideoAnalyticsGrpcTransport, transports.LiveVideoAnalyticsGrpcAsyncIOTransport]) +def test_live_video_analytics_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_live_video_analytics_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.LiveVideoAnalyticsRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_live_video_analytics_rest_lro_client(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_live_video_analytics_host_no_port(transport_name): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_live_video_analytics_host_with_port(transport_name): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_live_video_analytics_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LiveVideoAnalyticsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LiveVideoAnalyticsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_public_operators._session + session2 = client2.transport.list_public_operators._session + assert session1 != session2 + session1 = client1.transport.resolve_operator_info._session + session2 = client2.transport.resolve_operator_info._session + assert session1 != session2 + session1 = client1.transport.list_operators._session + session2 = client2.transport.list_operators._session + assert session1 != session2 + session1 = client1.transport.get_operator._session + session2 = client2.transport.get_operator._session + assert session1 != session2 + session1 = client1.transport.create_operator._session + session2 = client2.transport.create_operator._session + assert session1 != session2 + session1 = client1.transport.update_operator._session + session2 = client2.transport.update_operator._session + assert session1 != session2 + session1 = client1.transport.delete_operator._session + session2 = client2.transport.delete_operator._session + assert session1 != session2 + session1 = client1.transport.list_analyses._session + session2 = client2.transport.list_analyses._session + assert session1 != session2 + session1 = client1.transport.get_analysis._session + session2 = client2.transport.get_analysis._session + assert session1 != session2 + session1 = client1.transport.create_analysis._session + session2 = client2.transport.create_analysis._session + assert session1 != session2 + session1 = client1.transport.update_analysis._session + session2 = client2.transport.update_analysis._session + assert session1 != session2 + session1 = client1.transport.delete_analysis._session + session2 = client2.transport.delete_analysis._session + assert session1 != session2 + session1 = client1.transport.list_processes._session + session2 = client2.transport.list_processes._session + assert session1 != session2 + session1 = client1.transport.get_process._session + session2 = client2.transport.get_process._session + assert session1 != session2 + session1 = client1.transport.create_process._session + session2 = client2.transport.create_process._session + assert session1 != session2 + session1 = client1.transport.update_process._session + session2 = client2.transport.update_process._session + assert session1 != session2 + session1 = client1.transport.delete_process._session + session2 = client2.transport.delete_process._session + assert session1 != session2 + session1 = client1.transport.batch_run_process._session + session2 = client2.transport.batch_run_process._session + assert session1 != session2 +def test_live_video_analytics_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LiveVideoAnalyticsGrpcTransport( + 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_live_video_analytics_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LiveVideoAnalyticsGrpcAsyncIOTransport( + 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.LiveVideoAnalyticsGrpcTransport, transports.LiveVideoAnalyticsGrpcAsyncIOTransport]) +def test_live_video_analytics_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.LiveVideoAnalyticsGrpcTransport, transports.LiveVideoAnalyticsGrpcAsyncIOTransport]) +def test_live_video_analytics_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_live_video_analytics_grpc_lro_client(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_live_video_analytics_grpc_lro_async_client(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_analysis_path(): + project = "squid" + location = "clam" + cluster = "whelk" + analysis = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/analyses/{analysis}".format(project=project, location=location, cluster=cluster, analysis=analysis, ) + actual = LiveVideoAnalyticsClient.analysis_path(project, location, cluster, analysis) + assert expected == actual + + +def test_parse_analysis_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "analysis": "mussel", + } + path = LiveVideoAnalyticsClient.analysis_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_analysis_path(path) + assert expected == actual + +def test_cluster_path(): + project = "winkle" + location = "nautilus" + cluster = "scallop" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = LiveVideoAnalyticsClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "abalone", + "location": "squid", + "cluster": "clam", + } + path = LiveVideoAnalyticsClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_cluster_path(path) + assert expected == actual + +def test_operator_path(): + project = "whelk" + location = "octopus" + operator = "oyster" + expected = "projects/{project}/locations/{location}/operators/{operator}".format(project=project, location=location, operator=operator, ) + actual = LiveVideoAnalyticsClient.operator_path(project, location, operator) + assert expected == actual + + +def test_parse_operator_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "operator": "mussel", + } + path = LiveVideoAnalyticsClient.operator_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_operator_path(path) + assert expected == actual + +def test_process_path(): + project = "winkle" + location = "nautilus" + cluster = "scallop" + process = "abalone" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/processes/{process}".format(project=project, location=location, cluster=cluster, process=process, ) + actual = LiveVideoAnalyticsClient.process_path(project, location, cluster, process) + assert expected == actual + + +def test_parse_process_path(): + expected = { + "project": "squid", + "location": "clam", + "cluster": "whelk", + "process": "octopus", + } + path = LiveVideoAnalyticsClient.process_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_process_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LiveVideoAnalyticsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = LiveVideoAnalyticsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = LiveVideoAnalyticsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = LiveVideoAnalyticsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LiveVideoAnalyticsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = LiveVideoAnalyticsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = LiveVideoAnalyticsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = LiveVideoAnalyticsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LiveVideoAnalyticsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = LiveVideoAnalyticsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.LiveVideoAnalyticsTransport, '_prep_wrapped_messages') as prep: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LiveVideoAnalyticsTransport, '_prep_wrapped_messages') as prep: + transport_class = LiveVideoAnalyticsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_streaming_service.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_streaming_service.py new file mode 100644 index 000000000000..381626ff1fe7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_streaming_service.py @@ -0,0 +1,3942 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1.services.streaming_service import StreamingServiceAsyncClient +from google.cloud.visionai_v1.services.streaming_service import StreamingServiceClient +from google.cloud.visionai_v1.services.streaming_service import transports +from google.cloud.visionai_v1.types import streaming_resources +from google.cloud.visionai_v1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 StreamingServiceClient._get_default_mtls_endpoint(None) is None + assert StreamingServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert StreamingServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + StreamingServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert StreamingServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert StreamingServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamingServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert StreamingServiceClient._get_client_cert_source(None, False) is None + assert StreamingServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert StreamingServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert StreamingServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert StreamingServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert StreamingServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert StreamingServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamingServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert StreamingServiceClient._get_api_endpoint(None, None, default_universe, "always") == StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamingServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamingServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert StreamingServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamingServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert StreamingServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert StreamingServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert StreamingServiceClient._get_universe_domain(None, None) == StreamingServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + StreamingServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamingServiceClient, "grpc"), + (StreamingServiceAsyncClient, "grpc_asyncio"), + (StreamingServiceClient, "rest"), +]) +def test_streaming_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.StreamingServiceGrpcTransport, "grpc"), + (transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.StreamingServiceRestTransport, "rest"), +]) +def test_streaming_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamingServiceClient, "grpc"), + (StreamingServiceAsyncClient, "grpc_asyncio"), + (StreamingServiceClient, "rest"), +]) +def test_streaming_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_streaming_service_client_get_transport_class(): + transport = StreamingServiceClient.get_transport_class() + available_transports = [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceRestTransport, + ] + assert transport in available_transports + + transport = StreamingServiceClient.get_transport_class("grpc") + assert transport == transports.StreamingServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest"), +]) +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +def test_streaming_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(StreamingServiceClient, '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(StreamingServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", "true"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", "false"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest", "true"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_streaming_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + StreamingServiceClient, StreamingServiceAsyncClient +]) +@mock.patch.object(StreamingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingServiceAsyncClient)) +def test_streaming_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + StreamingServiceClient, StreamingServiceAsyncClient +]) +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +def test_streaming_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest"), +]) +def test_streaming_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", grpc_helpers), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest", None), +]) +def test_streaming_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_streaming_service_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1.services.streaming_service.transports.StreamingServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = StreamingServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", grpc_helpers), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_streaming_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.SendPacketsRequest, + dict, +]) +def test_send_packets(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([streaming_service.SendPacketsResponse()]) + response = client.send_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, streaming_service.SendPacketsResponse) + + +def test_send_packets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.send_packets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.send_packets] = mock_rpc + request = [{}] + client.send_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_send_packets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.send_packets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.send_packets] = mock_object + + request = [{}] + await client.send_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.send_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_send_packets_async(transport: str = 'grpc_asyncio', request_type=streaming_service.SendPacketsRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[streaming_service.SendPacketsResponse()]) + response = await client.send_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, streaming_service.SendPacketsResponse) + + +@pytest.mark.asyncio +async def test_send_packets_async_from_dict(): + await test_send_packets_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReceivePacketsRequest, + dict, +]) +def test_receive_packets(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([streaming_service.ReceivePacketsResponse()]) + response = client.receive_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, streaming_service.ReceivePacketsResponse) + + +def test_receive_packets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.receive_packets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.receive_packets] = mock_rpc + request = [{}] + client.receive_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.receive_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_receive_packets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.receive_packets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.receive_packets] = mock_object + + request = [{}] + await client.receive_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.receive_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_receive_packets_async(transport: str = 'grpc_asyncio', request_type=streaming_service.ReceivePacketsRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[streaming_service.ReceivePacketsResponse()]) + response = await client.receive_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, streaming_service.ReceivePacketsResponse) + + +@pytest.mark.asyncio +async def test_receive_packets_async_from_dict(): + await test_receive_packets_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReceiveEventsRequest, + dict, +]) +def test_receive_events(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([streaming_service.ReceiveEventsResponse()]) + response = client.receive_events(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, streaming_service.ReceiveEventsResponse) + + +def test_receive_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.receive_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.receive_events] = mock_rpc + request = [{}] + client.receive_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.receive_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_receive_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.receive_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.receive_events] = mock_object + + request = [{}] + await client.receive_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.receive_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_receive_events_async(transport: str = 'grpc_asyncio', request_type=streaming_service.ReceiveEventsRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[streaming_service.ReceiveEventsResponse()]) + response = await client.receive_events(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, streaming_service.ReceiveEventsResponse) + + +@pytest.mark.asyncio +async def test_receive_events_async_from_dict(): + await test_receive_events_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.AcquireLeaseRequest, + dict, +]) +def test_acquire_lease(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + response = client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streaming_service.AcquireLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +def test_acquire_lease_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 = StreamingServiceClient( + 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.acquire_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acquire_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.AcquireLeaseRequest() + + +def test_acquire_lease_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streaming_service.AcquireLeaseRequest( + series='series_value', + owner='owner_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acquire_lease(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.AcquireLeaseRequest( + series='series_value', + owner='owner_value', + ) + +def test_acquire_lease_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acquire_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acquire_lease] = mock_rpc + request = {} + client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acquire_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_acquire_lease_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.acquire_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.AcquireLeaseRequest() + +@pytest.mark.asyncio +async def test_acquire_lease_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.acquire_lease in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.acquire_lease] = mock_object + + request = {} + await client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.acquire_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_acquire_lease_async(transport: str = 'grpc_asyncio', request_type=streaming_service.AcquireLeaseRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streaming_service.AcquireLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +@pytest.mark.asyncio +async def test_acquire_lease_async_from_dict(): + await test_acquire_lease_async(request_type=dict) + + +def test_acquire_lease_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.AcquireLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + call.return_value = streaming_service.Lease() + client.acquire_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_acquire_lease_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.AcquireLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease()) + await client.acquire_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + streaming_service.RenewLeaseRequest, + dict, +]) +def test_renew_lease(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + response = client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streaming_service.RenewLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +def test_renew_lease_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 = StreamingServiceClient( + 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.renew_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.renew_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.RenewLeaseRequest() + + +def test_renew_lease_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streaming_service.RenewLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.renew_lease(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.RenewLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + +def test_renew_lease_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.renew_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.renew_lease] = mock_rpc + request = {} + client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.renew_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_renew_lease_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.renew_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.RenewLeaseRequest() + +@pytest.mark.asyncio +async def test_renew_lease_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.renew_lease in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.renew_lease] = mock_object + + request = {} + await client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.renew_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_renew_lease_async(transport: str = 'grpc_asyncio', request_type=streaming_service.RenewLeaseRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streaming_service.RenewLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +@pytest.mark.asyncio +async def test_renew_lease_async_from_dict(): + await test_renew_lease_async(request_type=dict) + + +def test_renew_lease_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.RenewLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + call.return_value = streaming_service.Lease() + client.renew_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_renew_lease_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.RenewLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease()) + await client.renew_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReleaseLeaseRequest, + dict, +]) +def test_release_lease(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streaming_service.ReleaseLeaseResponse( + ) + response = client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streaming_service.ReleaseLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.ReleaseLeaseResponse) + + +def test_release_lease_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 = StreamingServiceClient( + 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.release_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.release_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.ReleaseLeaseRequest() + + +def test_release_lease_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streaming_service.ReleaseLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.release_lease(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.ReleaseLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + +def test_release_lease_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.release_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.release_lease] = mock_rpc + request = {} + client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.release_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_release_lease_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.ReleaseLeaseResponse( + )) + response = await client.release_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.ReleaseLeaseRequest() + +@pytest.mark.asyncio +async def test_release_lease_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.release_lease in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.release_lease] = mock_object + + request = {} + await client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.release_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_release_lease_async(transport: str = 'grpc_asyncio', request_type=streaming_service.ReleaseLeaseRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.ReleaseLeaseResponse( + )) + response = await client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streaming_service.ReleaseLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.ReleaseLeaseResponse) + + +@pytest.mark.asyncio +async def test_release_lease_async_from_dict(): + await test_release_lease_async(request_type=dict) + + +def test_release_lease_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.ReleaseLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + call.return_value = streaming_service.ReleaseLeaseResponse() + client.release_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_release_lease_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.ReleaseLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.ReleaseLeaseResponse()) + await client.release_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +def test_send_packets_rest_no_http_options(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = streaming_service.SendPacketsRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.send_packets(requests) + + +def test_receive_packets_rest_no_http_options(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = streaming_service.ReceivePacketsRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.receive_packets(requests) + + +def test_receive_events_rest_no_http_options(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = streaming_service.ReceiveEventsRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.receive_events(requests) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.AcquireLeaseRequest, + dict, +]) +def test_acquire_lease_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streaming_service.Lease.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.acquire_lease(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + +def test_acquire_lease_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acquire_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acquire_lease] = mock_rpc + + request = {} + client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acquire_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_acquire_lease_rest_interceptors(null_interceptor): + transport = transports.StreamingServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamingServiceRestInterceptor(), + ) + client = StreamingServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "post_acquire_lease") as post, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "pre_acquire_lease") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streaming_service.AcquireLeaseRequest.pb(streaming_service.AcquireLeaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streaming_service.Lease.to_json(streaming_service.Lease()) + + request = streaming_service.AcquireLeaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streaming_service.Lease() + + client.acquire_lease(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_acquire_lease_rest_bad_request(transport: str = 'rest', request_type=streaming_service.AcquireLeaseRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.acquire_lease(request) + + +def test_acquire_lease_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.RenewLeaseRequest, + dict, +]) +def test_renew_lease_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streaming_service.Lease.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.renew_lease(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + +def test_renew_lease_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.renew_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.renew_lease] = mock_rpc + + request = {} + client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.renew_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_renew_lease_rest_interceptors(null_interceptor): + transport = transports.StreamingServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamingServiceRestInterceptor(), + ) + client = StreamingServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "post_renew_lease") as post, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "pre_renew_lease") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streaming_service.RenewLeaseRequest.pb(streaming_service.RenewLeaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streaming_service.Lease.to_json(streaming_service.Lease()) + + request = streaming_service.RenewLeaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streaming_service.Lease() + + client.renew_lease(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_renew_lease_rest_bad_request(transport: str = 'rest', request_type=streaming_service.RenewLeaseRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.renew_lease(request) + + +def test_renew_lease_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReleaseLeaseRequest, + dict, +]) +def test_release_lease_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streaming_service.ReleaseLeaseResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streaming_service.ReleaseLeaseResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.release_lease(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.ReleaseLeaseResponse) + +def test_release_lease_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.release_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.release_lease] = mock_rpc + + request = {} + client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.release_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_release_lease_rest_interceptors(null_interceptor): + transport = transports.StreamingServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamingServiceRestInterceptor(), + ) + client = StreamingServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "post_release_lease") as post, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "pre_release_lease") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streaming_service.ReleaseLeaseRequest.pb(streaming_service.ReleaseLeaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streaming_service.ReleaseLeaseResponse.to_json(streaming_service.ReleaseLeaseResponse()) + + request = streaming_service.ReleaseLeaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streaming_service.ReleaseLeaseResponse() + + client.release_lease(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_release_lease_rest_bad_request(transport: str = 'rest', request_type=streaming_service.ReleaseLeaseRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.release_lease(request) + + +def test_release_lease_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_send_packets_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.send_packets({}) + assert ( + "Method SendPackets is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_receive_packets_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.receive_packets({}) + assert ( + "Method ReceivePackets is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_receive_events_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.receive_events({}) + assert ( + "Method ReceiveEvents is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StreamingServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StreamingServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceGrpcAsyncIOTransport, + transports.StreamingServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = StreamingServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.StreamingServiceGrpcTransport, + ) + +def test_streaming_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.StreamingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_streaming_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1.services.streaming_service.transports.StreamingServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.StreamingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'send_packets', + 'receive_packets', + 'receive_events', + 'acquire_lease', + 'renew_lease', + 'release_lease', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_streaming_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1.services.streaming_service.transports.StreamingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamingServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_streaming_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1.services.streaming_service.transports.StreamingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamingServiceTransport() + adc.assert_called_once() + + +def test_streaming_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + StreamingServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceGrpcAsyncIOTransport, + ], +) +def test_streaming_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceGrpcAsyncIOTransport, + transports.StreamingServiceRestTransport, + ], +) +def test_streaming_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.StreamingServiceGrpcTransport, grpc_helpers), + (transports.StreamingServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_streaming_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.StreamingServiceGrpcTransport, transports.StreamingServiceGrpcAsyncIOTransport]) +def test_streaming_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_streaming_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.StreamingServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streaming_service_host_no_port(transport_name): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streaming_service_host_with_port(transport_name): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_streaming_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = StreamingServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = StreamingServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.send_packets._session + session2 = client2.transport.send_packets._session + assert session1 != session2 + session1 = client1.transport.receive_packets._session + session2 = client2.transport.receive_packets._session + assert session1 != session2 + session1 = client1.transport.receive_events._session + session2 = client2.transport.receive_events._session + assert session1 != session2 + session1 = client1.transport.acquire_lease._session + session2 = client2.transport.acquire_lease._session + assert session1 != session2 + session1 = client1.transport.renew_lease._session + session2 = client2.transport.renew_lease._session + assert session1 != session2 + session1 = client1.transport.release_lease._session + session2 = client2.transport.release_lease._session + assert session1 != session2 +def test_streaming_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamingServiceGrpcTransport( + 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_streaming_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamingServiceGrpcAsyncIOTransport( + 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.StreamingServiceGrpcTransport, transports.StreamingServiceGrpcAsyncIOTransport]) +def test_streaming_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.StreamingServiceGrpcTransport, transports.StreamingServiceGrpcAsyncIOTransport]) +def test_streaming_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_series_path(): + project = "squid" + location = "clam" + cluster = "whelk" + series = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + actual = StreamingServiceClient.series_path(project, location, cluster, series) + assert expected == actual + + +def test_parse_series_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "series": "mussel", + } + path = StreamingServiceClient.series_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_series_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = StreamingServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = StreamingServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = StreamingServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = StreamingServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = StreamingServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = StreamingServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = StreamingServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = StreamingServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = StreamingServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = StreamingServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.StreamingServiceTransport, '_prep_wrapped_messages') as prep: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.StreamingServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = StreamingServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_streams_service.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_streams_service.py new file mode 100644 index 000000000000..668754a68f7f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_streams_service.py @@ -0,0 +1,18693 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1.services.streams_service import StreamsServiceAsyncClient +from google.cloud.visionai_v1.services.streams_service import StreamsServiceClient +from google.cloud.visionai_v1.services.streams_service import pagers +from google.cloud.visionai_v1.services.streams_service import transports +from google.cloud.visionai_v1.types import common +from google.cloud.visionai_v1.types import streams_resources +from google.cloud.visionai_v1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 StreamsServiceClient._get_default_mtls_endpoint(None) is None + assert StreamsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert StreamsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + StreamsServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert StreamsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert StreamsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamsServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert StreamsServiceClient._get_client_cert_source(None, False) is None + assert StreamsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert StreamsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert StreamsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert StreamsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert StreamsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert StreamsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert StreamsServiceClient._get_api_endpoint(None, None, default_universe, "always") == StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert StreamsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamsServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert StreamsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert StreamsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert StreamsServiceClient._get_universe_domain(None, None) == StreamsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + StreamsServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamsServiceClient, "grpc"), + (StreamsServiceAsyncClient, "grpc_asyncio"), + (StreamsServiceClient, "rest"), +]) +def test_streams_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.StreamsServiceGrpcTransport, "grpc"), + (transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.StreamsServiceRestTransport, "rest"), +]) +def test_streams_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamsServiceClient, "grpc"), + (StreamsServiceAsyncClient, "grpc_asyncio"), + (StreamsServiceClient, "rest"), +]) +def test_streams_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_streams_service_client_get_transport_class(): + transport = StreamsServiceClient.get_transport_class() + available_transports = [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceRestTransport, + ] + assert transport in available_transports + + transport = StreamsServiceClient.get_transport_class("grpc") + assert transport == transports.StreamsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest"), +]) +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +def test_streams_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(StreamsServiceClient, '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(StreamsServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", "true"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", "false"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest", "true"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_streams_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + StreamsServiceClient, StreamsServiceAsyncClient +]) +@mock.patch.object(StreamsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamsServiceAsyncClient)) +def test_streams_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + StreamsServiceClient, StreamsServiceAsyncClient +]) +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +def test_streams_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest"), +]) +def test_streams_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", grpc_helpers), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest", None), +]) +def test_streams_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_streams_service_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1.services.streams_service.transports.StreamsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = StreamsServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", grpc_helpers), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_streams_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListClustersRequest, + dict, +]) +def test_list_clusters(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_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 = StreamsServiceClient( + 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_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListClustersRequest() + + +def test_list_clusters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListClustersRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_clusters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListClustersRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_clusters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc + request = {} + client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_clusters_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListClustersRequest() + +@pytest.mark.asyncio +async def test_list_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_clusters in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_clusters] = mock_object + + request = {} + await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_clusters_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListClustersRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_clusters_async_from_dict(): + await test_list_clusters_async(request_type=dict) + + +def test_list_clusters_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = streams_service.ListClustersResponse() + client.list_clusters(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_clusters_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse()) + await client.list_clusters(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_clusters_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_clusters( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_clusters_flattened_error(): + client = StreamsServiceClient( + 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_clusters( + streams_service.ListClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_clusters_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_clusters( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_clusters_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_clusters( + streams_service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_clusters(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, common.Cluster) + for i in results) +def test_list_clusters_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_clusters(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_clusters_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_clusters(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, common.Cluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_clusters_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_clusters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetClusterRequest, + dict, +]) +def test_get_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + ) + response = client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, common.Cluster) + assert response.name == 'name_value' + assert response.dataplane_service_endpoint == 'dataplane_service_endpoint_value' + assert response.state == common.Cluster.State.PROVISIONING + assert response.psc_target == 'psc_target_value' + + +def test_get_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetClusterRequest() + + +def test_get_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetClusterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetClusterRequest( + name='name_value', + ) + +def test_get_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc + request = {} + client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + )) + response = await client.get_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetClusterRequest() + +@pytest.mark.asyncio +async def test_get_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_cluster] = mock_object + + request = {} + await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + )) + response = await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, common.Cluster) + assert response.name == 'name_value' + assert response.dataplane_service_endpoint == 'dataplane_service_endpoint_value' + assert response.state == common.Cluster.State.PROVISIONING + assert response.psc_target == 'psc_target_value' + + +@pytest.mark.asyncio +async def test_get_cluster_async_from_dict(): + await test_get_cluster_async(request_type=dict) + + +def test_get_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = common.Cluster() + client.get_cluster(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_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster()) + await client.get_cluster(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_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = common.Cluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.GetClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = common.Cluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.GetClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateClusterRequest, + dict, +]) +def test_create_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateClusterRequest() + + +def test_create_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateClusterRequest( + parent='parent_value', + cluster_id='cluster_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateClusterRequest( + parent='parent_value', + cluster_id='cluster_id_value', + request_id='request_id_value', + ) + +def test_create_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc + request = {} + client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateClusterRequest() + +@pytest.mark.asyncio +async def test_create_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_cluster] = mock_object + + request = {} + await client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_cluster_async_from_dict(): + await test_create_cluster_async(request_type=dict) + + +def test_create_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_cluster(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_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_cluster(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_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_cluster( + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.CreateClusterRequest(), + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_cluster( + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.CreateClusterRequest(), + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateClusterRequest, + dict, +]) +def test_update_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateClusterRequest() + + +def test_update_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateClusterRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateClusterRequest( + request_id='request_id_value', + ) + +def test_update_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc + request = {} + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateClusterRequest() + +@pytest.mark.asyncio +async def test_update_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_cluster] = mock_object + + request = {} + await client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_cluster_async_from_dict(): + await test_update_cluster_async(request_type=dict) + + +def test_update_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_cluster(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', + 'cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_cluster(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', + 'cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_cluster( + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.UpdateClusterRequest(), + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_cluster( + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.UpdateClusterRequest(), + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteClusterRequest() + + +def test_delete_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteClusterRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteClusterRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc + request = {} + client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteClusterRequest() + +@pytest.mark.asyncio +async def test_delete_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_cluster] = mock_object + + request = {} + await client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_cluster_async_from_dict(): + await test_delete_cluster_async(request_type=dict) + + +def test_delete_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_cluster(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_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_cluster(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_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.DeleteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.DeleteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListStreamsRequest, + dict, +]) +def test_list_streams(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStreamsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_streams_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 = StreamsServiceClient( + 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_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListStreamsRequest() + + +def test_list_streams_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListStreamsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_streams(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListStreamsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_streams_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_streams] = mock_rpc + request = {} + client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_streams_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListStreamsRequest() + +@pytest.mark.asyncio +async def test_list_streams_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_streams in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_streams] = mock_object + + request = {} + await client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_streams_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListStreamsRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStreamsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_streams_async_from_dict(): + await test_list_streams_async(request_type=dict) + + +def test_list_streams_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + call.return_value = streams_service.ListStreamsResponse() + client.list_streams(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_streams_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse()) + await client.list_streams(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_streams_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListStreamsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_streams_flattened_error(): + client = StreamsServiceClient( + 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_streams( + streams_service.ListStreamsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_streams_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListStreamsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_streams_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_streams( + streams_service.ListStreamsRequest(), + parent='parent_value', + ) + + +def test_list_streams_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_streams(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Stream) + for i in results) +def test_list_streams_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + pages = list(client.list_streams(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_streams_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_streams(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, streams_resources.Stream) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_streams_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_streams(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetStreamRequest, + dict, +]) +def test_get_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + ) + response = client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Stream) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enable_hls_playback is True + assert response.media_warehouse_asset == 'media_warehouse_asset_value' + + +def test_get_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamRequest() + + +def test_get_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetStreamRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamRequest( + name='name_value', + ) + +def test_get_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_stream] = mock_rpc + request = {} + client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + )) + response = await client.get_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamRequest() + +@pytest.mark.asyncio +async def test_get_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_stream] = mock_object + + request = {} + await client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + )) + response = await client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Stream) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enable_hls_playback is True + assert response.media_warehouse_asset == 'media_warehouse_asset_value' + + +@pytest.mark.asyncio +async def test_get_stream_async_from_dict(): + await test_get_stream_async(request_type=dict) + + +def test_get_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + call.return_value = streams_resources.Stream() + client.get_stream(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_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream()) + await client.get_stream(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_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Stream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.GetStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Stream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.GetStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateStreamRequest, + dict, +]) +def test_create_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateStreamRequest() + + +def test_create_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateStreamRequest( + parent='parent_value', + stream_id='stream_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateStreamRequest( + parent='parent_value', + stream_id='stream_id_value', + request_id='request_id_value', + ) + +def test_create_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_stream] = mock_rpc + request = {} + client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateStreamRequest() + +@pytest.mark.asyncio +async def test_create_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_stream] = mock_object + + request = {} + await client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_stream_async_from_dict(): + await test_create_stream_async(request_type=dict) + + +def test_create_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_stream(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_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_stream(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_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_stream( + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].stream_id + mock_val = 'stream_id_value' + assert arg == mock_val + + +def test_create_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.CreateStreamRequest(), + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + +@pytest.mark.asyncio +async def test_create_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_stream( + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].stream_id + mock_val = 'stream_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.CreateStreamRequest(), + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateStreamRequest, + dict, +]) +def test_update_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateStreamRequest() + + +def test_update_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateStreamRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateStreamRequest( + request_id='request_id_value', + ) + +def test_update_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_stream] = mock_rpc + request = {} + client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateStreamRequest() + +@pytest.mark.asyncio +async def test_update_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_stream] = mock_object + + request = {} + await client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_stream_async_from_dict(): + await test_update_stream_async(request_type=dict) + + +def test_update_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateStreamRequest() + + request.stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_stream(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', + 'stream.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateStreamRequest() + + request.stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_stream(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', + 'stream.name=name_value', + ) in kw['metadata'] + + +def test_update_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_stream( + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.UpdateStreamRequest(), + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_stream( + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.UpdateStreamRequest(), + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteStreamRequest, + dict, +]) +def test_delete_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteStreamRequest() + + +def test_delete_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteStreamRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteStreamRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_stream] = mock_rpc + request = {} + client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteStreamRequest() + +@pytest.mark.asyncio +async def test_delete_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_stream] = mock_object + + request = {} + await client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_stream_async_from_dict(): + await test_delete_stream_async(request_type=dict) + + +def test_delete_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_stream(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_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_stream(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_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.DeleteStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.DeleteStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetStreamThumbnailRequest, + dict, +]) +def test_get_stream_thumbnail(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream_thumbnail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.get_stream_thumbnail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetStreamThumbnailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_get_stream_thumbnail_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 = StreamsServiceClient( + 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_stream_thumbnail), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_stream_thumbnail() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamThumbnailRequest() + + +def test_get_stream_thumbnail_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetStreamThumbnailRequest( + stream='stream_value', + gcs_object_name='gcs_object_name_value', + event='event_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream_thumbnail), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_stream_thumbnail(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamThumbnailRequest( + stream='stream_value', + gcs_object_name='gcs_object_name_value', + event='event_value', + request_id='request_id_value', + ) + +def test_get_stream_thumbnail_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_stream_thumbnail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_stream_thumbnail] = mock_rpc + request = {} + client.get_stream_thumbnail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.get_stream_thumbnail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_stream_thumbnail_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream_thumbnail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.get_stream_thumbnail() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamThumbnailRequest() + +@pytest.mark.asyncio +async def test_get_stream_thumbnail_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_stream_thumbnail in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_stream_thumbnail] = mock_object + + request = {} + await client.get_stream_thumbnail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.get_stream_thumbnail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_stream_thumbnail_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetStreamThumbnailRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream_thumbnail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.get_stream_thumbnail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetStreamThumbnailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_get_stream_thumbnail_async_from_dict(): + await test_get_stream_thumbnail_async(request_type=dict) + + +def test_get_stream_thumbnail_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetStreamThumbnailRequest() + + request.stream = 'stream_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream_thumbnail), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.get_stream_thumbnail(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', + 'stream=stream_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_stream_thumbnail_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetStreamThumbnailRequest() + + request.stream = 'stream_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream_thumbnail), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.get_stream_thumbnail(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', + 'stream=stream_value', + ) in kw['metadata'] + + +def test_get_stream_thumbnail_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream_thumbnail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_stream_thumbnail( + stream='stream_value', + gcs_object_name='gcs_object_name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = 'stream_value' + assert arg == mock_val + arg = args[0].gcs_object_name + mock_val = 'gcs_object_name_value' + assert arg == mock_val + + +def test_get_stream_thumbnail_flattened_error(): + client = StreamsServiceClient( + 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_stream_thumbnail( + streams_service.GetStreamThumbnailRequest(), + stream='stream_value', + gcs_object_name='gcs_object_name_value', + ) + +@pytest.mark.asyncio +async def test_get_stream_thumbnail_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream_thumbnail), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_stream_thumbnail( + stream='stream_value', + gcs_object_name='gcs_object_name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = 'stream_value' + assert arg == mock_val + arg = args[0].gcs_object_name + mock_val = 'gcs_object_name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_stream_thumbnail_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream_thumbnail( + streams_service.GetStreamThumbnailRequest(), + stream='stream_value', + gcs_object_name='gcs_object_name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.GenerateStreamHlsTokenRequest, + dict, +]) +def test_generate_stream_hls_token(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + ) + response = client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GenerateStreamHlsTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_service.GenerateStreamHlsTokenResponse) + assert response.token == 'token_value' + + +def test_generate_stream_hls_token_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 = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_stream_hls_token() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GenerateStreamHlsTokenRequest() + + +def test_generate_stream_hls_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GenerateStreamHlsTokenRequest( + stream='stream_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_stream_hls_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GenerateStreamHlsTokenRequest( + stream='stream_value', + ) + +def test_generate_stream_hls_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_stream_hls_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_stream_hls_token] = mock_rpc + request = {} + client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_stream_hls_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + )) + response = await client.generate_stream_hls_token() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GenerateStreamHlsTokenRequest() + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_stream_hls_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.generate_stream_hls_token] = mock_object + + request = {} + await client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.generate_stream_hls_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_async(transport: str = 'grpc_asyncio', request_type=streams_service.GenerateStreamHlsTokenRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + )) + response = await client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GenerateStreamHlsTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_service.GenerateStreamHlsTokenResponse) + assert response.token == 'token_value' + + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_async_from_dict(): + await test_generate_stream_hls_token_async(request_type=dict) + + +def test_generate_stream_hls_token_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GenerateStreamHlsTokenRequest() + + request.stream = 'stream_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value = streams_service.GenerateStreamHlsTokenResponse() + client.generate_stream_hls_token(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', + 'stream=stream_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GenerateStreamHlsTokenRequest() + + request.stream = 'stream_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse()) + await client.generate_stream_hls_token(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', + 'stream=stream_value', + ) in kw['metadata'] + + +def test_generate_stream_hls_token_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.GenerateStreamHlsTokenResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_stream_hls_token( + stream='stream_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = 'stream_value' + assert arg == mock_val + + +def test_generate_stream_hls_token_flattened_error(): + client = StreamsServiceClient( + 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.generate_stream_hls_token( + streams_service.GenerateStreamHlsTokenRequest(), + stream='stream_value', + ) + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.GenerateStreamHlsTokenResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_stream_hls_token( + stream='stream_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = 'stream_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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.generate_stream_hls_token( + streams_service.GenerateStreamHlsTokenRequest(), + stream='stream_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListEventsRequest, + dict, +]) +def test_list_events(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_events_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 = StreamsServiceClient( + 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_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListEventsRequest() + + +def test_list_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListEventsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListEventsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_events] = mock_rpc + request = {} + client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListEventsRequest() + +@pytest.mark.asyncio +async def test_list_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_events] = mock_object + + request = {} + await client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_events_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListEventsRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_events_async_from_dict(): + await test_list_events_async(request_type=dict) + + +def test_list_events_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + call.return_value = streams_service.ListEventsResponse() + client.list_events(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_events_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse()) + await client.list_events(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_events_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_events_flattened_error(): + client = StreamsServiceClient( + 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_events( + streams_service.ListEventsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_events_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_events_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_events( + streams_service.ListEventsRequest(), + parent='parent_value', + ) + + +def test_list_events_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_events(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Event) + for i in results) +def test_list_events_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + pages = list(client.list_events(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_events_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, streams_resources.Event) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_events_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetEventRequest, + dict, +]) +def test_get_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + ) + response = client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Event) + assert response.name == 'name_value' + assert response.alignment_clock == streams_resources.Event.Clock.CAPTURE + + +def test_get_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetEventRequest() + + +def test_get_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetEventRequest( + name='name_value', + ) + +def test_get_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event] = mock_rpc + request = {} + client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + )) + response = await client.get_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetEventRequest() + +@pytest.mark.asyncio +async def test_get_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_event] = mock_object + + request = {} + await client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + )) + response = await client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Event) + assert response.name == 'name_value' + assert response.alignment_clock == streams_resources.Event.Clock.CAPTURE + + +@pytest.mark.asyncio +async def test_get_event_async_from_dict(): + await test_get_event_async(request_type=dict) + + +def test_get_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + call.return_value = streams_resources.Event() + client.get_event(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_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event()) + await client.get_event(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_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Event() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.GetEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Event() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.GetEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateEventRequest, + dict, +]) +def test_create_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateEventRequest() + + +def test_create_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateEventRequest( + parent='parent_value', + event_id='event_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateEventRequest( + parent='parent_value', + event_id='event_id_value', + request_id='request_id_value', + ) + +def test_create_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event] = mock_rpc + request = {} + client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateEventRequest() + +@pytest.mark.asyncio +async def test_create_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_event] = mock_object + + request = {} + await client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_event_async_from_dict(): + await test_create_event_async(request_type=dict) + + +def test_create_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_event(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_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_event(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_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_event( + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].event_id + mock_val = 'event_id_value' + assert arg == mock_val + + +def test_create_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.CreateEventRequest(), + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + +@pytest.mark.asyncio +async def test_create_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_event( + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].event_id + mock_val = 'event_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.CreateEventRequest(), + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateEventRequest, + dict, +]) +def test_update_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateEventRequest() + + +def test_update_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateEventRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateEventRequest( + request_id='request_id_value', + ) + +def test_update_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event] = mock_rpc + request = {} + client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateEventRequest() + +@pytest.mark.asyncio +async def test_update_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_event] = mock_object + + request = {} + await client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_event_async_from_dict(): + await test_update_event_async(request_type=dict) + + +def test_update_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateEventRequest() + + request.event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_event(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', + 'event.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateEventRequest() + + request.event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_event(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', + 'event.name=name_value', + ) in kw['metadata'] + + +def test_update_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_event( + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.UpdateEventRequest(), + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_event( + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.UpdateEventRequest(), + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteEventRequest, + dict, +]) +def test_delete_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteEventRequest() + + +def test_delete_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteEventRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteEventRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event] = mock_rpc + request = {} + client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteEventRequest() + +@pytest.mark.asyncio +async def test_delete_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_event] = mock_object + + request = {} + await client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_event_async_from_dict(): + await test_delete_event_async(request_type=dict) + + +def test_delete_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_event(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_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_event(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_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.DeleteEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.DeleteEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListSeriesRequest, + dict, +]) +def test_list_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSeriesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListSeriesRequest() + + +def test_list_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListSeriesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListSeriesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_series] = mock_rpc + request = {} + client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListSeriesRequest() + +@pytest.mark.asyncio +async def test_list_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_series] = mock_object + + request = {} + await client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSeriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_series_async_from_dict(): + await test_list_series_async(request_type=dict) + + +def test_list_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + call.return_value = streams_service.ListSeriesResponse() + client.list_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse()) + await client.list_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListSeriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_series( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.ListSeriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListSeriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_series( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.ListSeriesRequest(), + parent='parent_value', + ) + + +def test_list_series_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_series(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Series) + for i in results) +def test_list_series_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + pages = list(client.list_series(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_series_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_series(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, streams_resources.Series) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_series_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_series(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetSeriesRequest, + dict, +]) +def test_get_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + ) + response = client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Series) + assert response.name == 'name_value' + assert response.stream == 'stream_value' + assert response.event == 'event_value' + + +def test_get_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetSeriesRequest() + + +def test_get_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetSeriesRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetSeriesRequest( + name='name_value', + ) + +def test_get_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_series] = mock_rpc + request = {} + client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + )) + response = await client.get_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetSeriesRequest() + +@pytest.mark.asyncio +async def test_get_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_series] = mock_object + + request = {} + await client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + )) + response = await client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Series) + assert response.name == 'name_value' + assert response.stream == 'stream_value' + assert response.event == 'event_value' + + +@pytest.mark.asyncio +async def test_get_series_async_from_dict(): + await test_get_series_async(request_type=dict) + + +def test_get_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + call.return_value = streams_resources.Series() + client.get_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series()) + await client.get_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Series() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.GetSeriesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Series() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.GetSeriesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateSeriesRequest, + dict, +]) +def test_create_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateSeriesRequest() + + +def test_create_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateSeriesRequest( + parent='parent_value', + series_id='series_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateSeriesRequest( + parent='parent_value', + series_id='series_id_value', + request_id='request_id_value', + ) + +def test_create_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_series] = mock_rpc + request = {} + client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateSeriesRequest() + +@pytest.mark.asyncio +async def test_create_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_series] = mock_object + + request = {} + await client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_series_async_from_dict(): + await test_create_series_async(request_type=dict) + + +def test_create_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_series( + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].series_id + mock_val = 'series_id_value' + assert arg == mock_val + + +def test_create_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.CreateSeriesRequest(), + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + +@pytest.mark.asyncio +async def test_create_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_series( + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].series_id + mock_val = 'series_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.CreateSeriesRequest(), + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateSeriesRequest, + dict, +]) +def test_update_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateSeriesRequest() + + +def test_update_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateSeriesRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateSeriesRequest( + request_id='request_id_value', + ) + +def test_update_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_series] = mock_rpc + request = {} + client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateSeriesRequest() + +@pytest.mark.asyncio +async def test_update_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_series] = mock_object + + request = {} + await client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_series_async_from_dict(): + await test_update_series_async(request_type=dict) + + +def test_update_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateSeriesRequest() + + request.series.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_series(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', + 'series.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateSeriesRequest() + + request.series.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_series(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', + 'series.name=name_value', + ) in kw['metadata'] + + +def test_update_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_series( + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.UpdateSeriesRequest(), + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_series( + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.UpdateSeriesRequest(), + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteSeriesRequest, + dict, +]) +def test_delete_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteSeriesRequest() + + +def test_delete_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteSeriesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteSeriesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_series] = mock_rpc + request = {} + client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteSeriesRequest() + +@pytest.mark.asyncio +async def test_delete_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_series] = mock_object + + request = {} + await client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_series_async_from_dict(): + await test_delete_series_async(request_type=dict) + + +def test_delete_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.DeleteSeriesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.DeleteSeriesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.MaterializeChannelRequest, + dict, +]) +def test_materialize_channel(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.MaterializeChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_materialize_channel_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 = StreamsServiceClient( + 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.materialize_channel), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.materialize_channel() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.MaterializeChannelRequest() + + +def test_materialize_channel_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.MaterializeChannelRequest( + parent='parent_value', + channel_id='channel_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.materialize_channel(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.MaterializeChannelRequest( + parent='parent_value', + channel_id='channel_id_value', + request_id='request_id_value', + ) + +def test_materialize_channel_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.materialize_channel in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.materialize_channel] = mock_rpc + request = {} + client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.materialize_channel(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_materialize_channel_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.materialize_channel() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.MaterializeChannelRequest() + +@pytest.mark.asyncio +async def test_materialize_channel_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.materialize_channel in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.materialize_channel] = mock_object + + request = {} + await client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.materialize_channel(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_materialize_channel_async(transport: str = 'grpc_asyncio', request_type=streams_service.MaterializeChannelRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.MaterializeChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_materialize_channel_async_from_dict(): + await test_materialize_channel_async(request_type=dict) + + +def test_materialize_channel_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.MaterializeChannelRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.materialize_channel(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_materialize_channel_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.MaterializeChannelRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.materialize_channel(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_materialize_channel_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.materialize_channel( + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].channel + mock_val = streams_resources.Channel(name='name_value') + assert arg == mock_val + arg = args[0].channel_id + mock_val = 'channel_id_value' + assert arg == mock_val + + +def test_materialize_channel_flattened_error(): + client = StreamsServiceClient( + 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.materialize_channel( + streams_service.MaterializeChannelRequest(), + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + +@pytest.mark.asyncio +async def test_materialize_channel_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.materialize_channel( + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].channel + mock_val = streams_resources.Channel(name='name_value') + assert arg == mock_val + arg = args[0].channel_id + mock_val = 'channel_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_materialize_channel_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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.materialize_channel( + streams_service.MaterializeChannelRequest(), + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListClustersRequest, + dict, +]) +def test_list_clusters_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc + + request = {} + client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_clusters_rest_required_fields(request_type=streams_service.ListClustersRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_clusters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_clusters_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_clusters") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListClustersRequest.pb(streams_service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListClustersResponse.to_json(streams_service.ListClustersResponse()) + + request = streams_service.ListClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListClustersResponse() + + client.list_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListClustersRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_clusters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, args[1]) + + +def test_list_clusters_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_clusters( + streams_service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListClustersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, common.Cluster) + for i in results) + + pages = list(client.list_clusters(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetClusterRequest, + dict, +]) +def test_get_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = common.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.Cluster) + assert response.name == 'name_value' + assert response.dataplane_service_endpoint == 'dataplane_service_endpoint_value' + assert response.state == common.Cluster.State.PROVISIONING + assert response.psc_target == 'psc_target_value' + +def test_get_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc + + request = {} + client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_cluster_rest_required_fields(request_type=streams_service.GetClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = common.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetClusterRequest.pb(streams_service.GetClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = common.Cluster.to_json(common.Cluster()) + + request = streams_service.GetClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.Cluster() + + client.get_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_cluster(request) + + +def test_get_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = common.Cluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = common.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_get_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_cluster( + streams_service.GetClusterRequest(), + name='name_value', + ) + + +def test_get_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateClusterRequest, + dict, +]) +def test_create_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'dataplane_service_endpoint': 'dataplane_service_endpoint_value', 'state': 1, 'psc_target': 'psc_target_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc + + request = {} + client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_cluster_rest_required_fields(request_type=streams_service.CreateClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateClusterRequest.pb(streams_service.CreateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_cluster(request) + + +def test_create_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, args[1]) + + +def test_create_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_cluster( + streams_service.CreateClusterRequest(), + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + +def test_create_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateClusterRequest, + dict, +]) +def test_update_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'dataplane_service_endpoint': 'dataplane_service_endpoint_value', 'state': 1, 'psc_target': 'psc_target_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc + + request = {} + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_cluster_rest_required_fields(request_type=streams_service.UpdateClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateClusterRequest.pb(streams_service.UpdateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_cluster(request) + + +def test_update_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{cluster.name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_update_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_cluster( + streams_service.UpdateClusterRequest(), + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc + + request = {} + client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_cluster_rest_required_fields(request_type=streams_service.DeleteClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteClusterRequest.pb(streams_service.DeleteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_cluster(request) + + +def test_delete_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_delete_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_cluster( + streams_service.DeleteClusterRequest(), + name='name_value', + ) + + +def test_delete_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListStreamsRequest, + dict, +]) +def test_list_streams_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_streams(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStreamsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_streams_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_streams] = mock_rpc + + request = {} + client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_streams_rest_required_fields(request_type=streams_service.ListStreamsRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_streams._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_streams._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListStreamsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_streams(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_streams_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_streams._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_streams_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_streams") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_streams") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListStreamsRequest.pb(streams_service.ListStreamsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListStreamsResponse.to_json(streams_service.ListStreamsResponse()) + + request = streams_service.ListStreamsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListStreamsResponse() + + client.list_streams(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_streams_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListStreamsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_streams(request) + + +def test_list_streams_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListStreamsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_streams(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/streams" % client.transport._host, args[1]) + + +def test_list_streams_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_streams( + streams_service.ListStreamsRequest(), + parent='parent_value', + ) + + +def test_list_streams_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListStreamsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_streams(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Stream) + for i in results) + + pages = list(client.list_streams(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetStreamRequest, + dict, +]) +def test_get_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Stream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Stream) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enable_hls_playback is True + assert response.media_warehouse_asset == 'media_warehouse_asset_value' + +def test_get_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_stream] = mock_rpc + + request = {} + client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_stream_rest_required_fields(request_type=streams_service.GetStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_resources.Stream() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_resources.Stream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetStreamRequest.pb(streams_service.GetStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_resources.Stream.to_json(streams_resources.Stream()) + + request = streams_service.GetStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_resources.Stream() + + client.get_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_stream(request) + + +def test_get_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Stream() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Stream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/streams/*}" % client.transport._host, args[1]) + + +def test_get_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_stream( + streams_service.GetStreamRequest(), + name='name_value', + ) + + +def test_get_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateStreamRequest, + dict, +]) +def test_create_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["stream"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'enable_hls_playback': True, 'media_warehouse_asset': 'media_warehouse_asset_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateStreamRequest.meta.fields["stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["stream"][field])): + del request_init["stream"][field][i][subfield] + else: + del request_init["stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_stream(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_stream] = mock_rpc + + request = {} + client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_stream_rest_required_fields(request_type=streams_service.CreateStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["stream_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "streamId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "streamId" in jsonified_request + assert jsonified_request["streamId"] == request_init["stream_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["streamId"] = 'stream_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_stream._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "stream_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "streamId" in jsonified_request + assert jsonified_request["streamId"] == 'stream_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_stream(request) + + expected_params = [ + ( + "streamId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "streamId", )) & set(("parent", "streamId", "stream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateStreamRequest.pb(streams_service.CreateStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_stream(request) + + +def test_create_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/streams" % client.transport._host, args[1]) + + +def test_create_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_stream( + streams_service.CreateStreamRequest(), + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + +def test_create_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateStreamRequest, + dict, +]) +def test_update_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'stream': {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'}} + request_init["stream"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'enable_hls_playback': True, 'media_warehouse_asset': 'media_warehouse_asset_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateStreamRequest.meta.fields["stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["stream"][field])): + del request_init["stream"][field][i][subfield] + else: + del request_init["stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_stream(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_stream] = mock_rpc + + request = {} + client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_stream_rest_required_fields(request_type=streams_service.UpdateStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_stream._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "stream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateStreamRequest.pb(streams_service.UpdateStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'stream': {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_stream(request) + + +def test_update_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'stream': {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{stream.name=projects/*/locations/*/clusters/*/streams/*}" % client.transport._host, args[1]) + + +def test_update_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_stream( + streams_service.UpdateStreamRequest(), + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteStreamRequest, + dict, +]) +def test_delete_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_stream(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_stream] = mock_rpc + + request = {} + client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_stream_rest_required_fields(request_type=streams_service.DeleteStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_stream._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteStreamRequest.pb(streams_service.DeleteStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_stream(request) + + +def test_delete_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/streams/*}" % client.transport._host, args[1]) + + +def test_delete_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_stream( + streams_service.DeleteStreamRequest(), + name='name_value', + ) + + +def test_delete_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetStreamThumbnailRequest, + dict, +]) +def test_get_stream_thumbnail_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_stream_thumbnail(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_get_stream_thumbnail_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_stream_thumbnail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_stream_thumbnail] = mock_rpc + + request = {} + client.get_stream_thumbnail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.get_stream_thumbnail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_stream_thumbnail_rest_required_fields(request_type=streams_service.GetStreamThumbnailRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["stream"] = "" + request_init["gcs_object_name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_stream_thumbnail._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["stream"] = 'stream_value' + jsonified_request["gcsObjectName"] = 'gcs_object_name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_stream_thumbnail._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "stream" in jsonified_request + assert jsonified_request["stream"] == 'stream_value' + assert "gcsObjectName" in jsonified_request + assert jsonified_request["gcsObjectName"] == 'gcs_object_name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_stream_thumbnail(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_stream_thumbnail_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_stream_thumbnail._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("stream", "gcsObjectName", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_stream_thumbnail_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_stream_thumbnail") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_stream_thumbnail") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetStreamThumbnailRequest.pb(streams_service.GetStreamThumbnailRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.GetStreamThumbnailRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.get_stream_thumbnail(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_stream_thumbnail_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetStreamThumbnailRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_stream_thumbnail(request) + + +def test_get_stream_thumbnail_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + stream='stream_value', + gcs_object_name='gcs_object_name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_stream_thumbnail(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{stream=projects/*/locations/*/clusters/*/streams/*}:getThumbnail" % client.transport._host, args[1]) + + +def test_get_stream_thumbnail_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_stream_thumbnail( + streams_service.GetStreamThumbnailRequest(), + stream='stream_value', + gcs_object_name='gcs_object_name_value', + ) + + +def test_get_stream_thumbnail_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.GenerateStreamHlsTokenRequest, + dict, +]) +def test_generate_stream_hls_token_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.GenerateStreamHlsTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_stream_hls_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_service.GenerateStreamHlsTokenResponse) + assert response.token == 'token_value' + +def test_generate_stream_hls_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_stream_hls_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_stream_hls_token] = mock_rpc + + request = {} + client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_stream_hls_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_stream_hls_token_rest_required_fields(request_type=streams_service.GenerateStreamHlsTokenRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["stream"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_stream_hls_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["stream"] = 'stream_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_stream_hls_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "stream" in jsonified_request + assert jsonified_request["stream"] == 'stream_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.GenerateStreamHlsTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.GenerateStreamHlsTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.generate_stream_hls_token(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_stream_hls_token_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_stream_hls_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("stream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_stream_hls_token_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_generate_stream_hls_token") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_generate_stream_hls_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GenerateStreamHlsTokenRequest.pb(streams_service.GenerateStreamHlsTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.GenerateStreamHlsTokenResponse.to_json(streams_service.GenerateStreamHlsTokenResponse()) + + request = streams_service.GenerateStreamHlsTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.GenerateStreamHlsTokenResponse() + + client.generate_stream_hls_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_stream_hls_token_rest_bad_request(transport: str = 'rest', request_type=streams_service.GenerateStreamHlsTokenRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_stream_hls_token(request) + + +def test_generate_stream_hls_token_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.GenerateStreamHlsTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + stream='stream_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.GenerateStreamHlsTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.generate_stream_hls_token(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{stream=projects/*/locations/*/clusters/*/streams/*}:generateStreamHlsToken" % client.transport._host, args[1]) + + +def test_generate_stream_hls_token_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_stream_hls_token( + streams_service.GenerateStreamHlsTokenRequest(), + stream='stream_value', + ) + + +def test_generate_stream_hls_token_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListEventsRequest, + dict, +]) +def test_list_events_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_events] = mock_rpc + + request = {} + client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_events_rest_required_fields(request_type=streams_service.ListEventsRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListEventsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_events_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_events_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_events") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListEventsRequest.pb(streams_service.ListEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListEventsResponse.to_json(streams_service.ListEventsResponse()) + + request = streams_service.ListEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListEventsResponse() + + client.list_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_events_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListEventsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_events(request) + + +def test_list_events_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/events" % client.transport._host, args[1]) + + +def test_list_events_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_events( + streams_service.ListEventsRequest(), + parent='parent_value', + ) + + +def test_list_events_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListEventsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Event) + for i in results) + + pages = list(client.list_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetEventRequest, + dict, +]) +def test_get_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Event.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Event) + assert response.name == 'name_value' + assert response.alignment_clock == streams_resources.Event.Clock.CAPTURE + +def test_get_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event] = mock_rpc + + request = {} + client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_event_rest_required_fields(request_type=streams_service.GetEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_resources.Event() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_resources.Event.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetEventRequest.pb(streams_service.GetEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_resources.Event.to_json(streams_resources.Event()) + + request = streams_service.GetEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_resources.Event() + + client.get_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_event(request) + + +def test_get_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Event() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Event.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/events/*}" % client.transport._host, args[1]) + + +def test_get_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_event( + streams_service.GetEventRequest(), + name='name_value', + ) + + +def test_get_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateEventRequest, + dict, +]) +def test_create_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["event"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'alignment_clock': 1, 'grace_period': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateEventRequest.meta.fields["event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event"][field])): + del request_init["event"][field][i][subfield] + else: + del request_init["event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_event(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event] = mock_rpc + + request = {} + client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_event_rest_required_fields(request_type=streams_service.CreateEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["event_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "eventId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "eventId" in jsonified_request + assert jsonified_request["eventId"] == request_init["event_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["eventId"] = 'event_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("event_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "eventId" in jsonified_request + assert jsonified_request["eventId"] == 'event_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_event(request) + + expected_params = [ + ( + "eventId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("eventId", "requestId", )) & set(("parent", "eventId", "event", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateEventRequest.pb(streams_service.CreateEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_event(request) + + +def test_create_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/events" % client.transport._host, args[1]) + + +def test_create_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_event( + streams_service.CreateEventRequest(), + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + +def test_create_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateEventRequest, + dict, +]) +def test_update_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'event': {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'}} + request_init["event"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'alignment_clock': 1, 'grace_period': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateEventRequest.meta.fields["event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event"][field])): + del request_init["event"][field][i][subfield] + else: + del request_init["event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_event(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event] = mock_rpc + + request = {} + client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_event_rest_required_fields(request_type=streams_service.UpdateEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "event", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateEventRequest.pb(streams_service.UpdateEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'event': {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_event(request) + + +def test_update_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'event': {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{event.name=projects/*/locations/*/clusters/*/events/*}" % client.transport._host, args[1]) + + +def test_update_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_event( + streams_service.UpdateEventRequest(), + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteEventRequest, + dict, +]) +def test_delete_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_event(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event] = mock_rpc + + request = {} + client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_event_rest_required_fields(request_type=streams_service.DeleteEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteEventRequest.pb(streams_service.DeleteEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_event(request) + + +def test_delete_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/events/*}" % client.transport._host, args[1]) + + +def test_delete_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_event( + streams_service.DeleteEventRequest(), + name='name_value', + ) + + +def test_delete_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListSeriesRequest, + dict, +]) +def test_list_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListSeriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_series(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSeriesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_series] = mock_rpc + + request = {} + client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_series_rest_required_fields(request_type=streams_service.ListSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListSeriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListSeriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListSeriesRequest.pb(streams_service.ListSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListSeriesResponse.to_json(streams_service.ListSeriesResponse()) + + request = streams_service.ListSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListSeriesResponse() + + client.list_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_series(request) + + +def test_list_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListSeriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListSeriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/series" % client.transport._host, args[1]) + + +def test_list_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_series( + streams_service.ListSeriesRequest(), + parent='parent_value', + ) + + +def test_list_series_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListSeriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_series(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Series) + for i in results) + + pages = list(client.list_series(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetSeriesRequest, + dict, +]) +def test_get_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Series.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_series(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Series) + assert response.name == 'name_value' + assert response.stream == 'stream_value' + assert response.event == 'event_value' + +def test_get_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_series] = mock_rpc + + request = {} + client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_series_rest_required_fields(request_type=streams_service.GetSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_resources.Series() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_resources.Series.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetSeriesRequest.pb(streams_service.GetSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_resources.Series.to_json(streams_resources.Series()) + + request = streams_service.GetSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_resources.Series() + + client.get_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_series(request) + + +def test_get_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Series() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Series.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/series/*}" % client.transport._host, args[1]) + + +def test_get_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_series( + streams_service.GetSeriesRequest(), + name='name_value', + ) + + +def test_get_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateSeriesRequest, + dict, +]) +def test_create_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["series"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'stream': 'stream_value', 'event': 'event_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateSeriesRequest.meta.fields["series"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["series"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["series"][field])): + del request_init["series"][field][i][subfield] + else: + del request_init["series"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_series(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_series] = mock_rpc + + request = {} + client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_series_rest_required_fields(request_type=streams_service.CreateSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["series_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "seriesId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "seriesId" in jsonified_request + assert jsonified_request["seriesId"] == request_init["series_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["seriesId"] = 'series_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "series_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "seriesId" in jsonified_request + assert jsonified_request["seriesId"] == 'series_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_series(request) + + expected_params = [ + ( + "seriesId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "seriesId", )) & set(("parent", "seriesId", "series", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateSeriesRequest.pb(streams_service.CreateSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_series(request) + + +def test_create_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/series" % client.transport._host, args[1]) + + +def test_create_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_series( + streams_service.CreateSeriesRequest(), + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + +def test_create_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateSeriesRequest, + dict, +]) +def test_update_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'}} + request_init["series"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'stream': 'stream_value', 'event': 'event_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateSeriesRequest.meta.fields["series"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["series"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["series"][field])): + del request_init["series"][field][i][subfield] + else: + del request_init["series"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_series(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_series] = mock_rpc + + request = {} + client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_series_rest_required_fields(request_type=streams_service.UpdateSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "series", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateSeriesRequest.pb(streams_service.UpdateSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_series(request) + + +def test_update_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'series': {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{series.name=projects/*/locations/*/clusters/*/series/*}" % client.transport._host, args[1]) + + +def test_update_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_series( + streams_service.UpdateSeriesRequest(), + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteSeriesRequest, + dict, +]) +def test_delete_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_series(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_series] = mock_rpc + + request = {} + client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_series_rest_required_fields(request_type=streams_service.DeleteSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteSeriesRequest.pb(streams_service.DeleteSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_series(request) + + +def test_delete_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/series/*}" % client.transport._host, args[1]) + + +def test_delete_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_series( + streams_service.DeleteSeriesRequest(), + name='name_value', + ) + + +def test_delete_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.MaterializeChannelRequest, + dict, +]) +def test_materialize_channel_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["channel"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'stream': 'stream_value', 'event': 'event_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.MaterializeChannelRequest.meta.fields["channel"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["channel"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["channel"][field])): + del request_init["channel"][field][i][subfield] + else: + del request_init["channel"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.materialize_channel(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_materialize_channel_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.materialize_channel in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.materialize_channel] = mock_rpc + + request = {} + client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.materialize_channel(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_materialize_channel_rest_required_fields(request_type=streams_service.MaterializeChannelRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["channel_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "channelId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).materialize_channel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == request_init["channel_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["channelId"] = 'channel_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).materialize_channel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("channel_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == 'channel_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.materialize_channel(request) + + expected_params = [ + ( + "channelId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_materialize_channel_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.materialize_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(("channelId", "requestId", )) & set(("parent", "channelId", "channel", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_materialize_channel_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_materialize_channel") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_materialize_channel") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.MaterializeChannelRequest.pb(streams_service.MaterializeChannelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.MaterializeChannelRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.materialize_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_materialize_channel_rest_bad_request(transport: str = 'rest', request_type=streams_service.MaterializeChannelRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.materialize_channel(request) + + +def test_materialize_channel_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.materialize_channel(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/channels" % client.transport._host, args[1]) + + +def test_materialize_channel_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.materialize_channel( + streams_service.MaterializeChannelRequest(), + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + +def test_materialize_channel_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StreamsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StreamsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceGrpcAsyncIOTransport, + transports.StreamsServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = StreamsServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.StreamsServiceGrpcTransport, + ) + +def test_streams_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.StreamsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_streams_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1.services.streams_service.transports.StreamsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.StreamsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_clusters', + 'get_cluster', + 'create_cluster', + 'update_cluster', + 'delete_cluster', + 'list_streams', + 'get_stream', + 'create_stream', + 'update_stream', + 'delete_stream', + 'get_stream_thumbnail', + 'generate_stream_hls_token', + 'list_events', + 'get_event', + 'create_event', + 'update_event', + 'delete_event', + 'list_series', + 'get_series', + 'create_series', + 'update_series', + 'delete_series', + 'materialize_channel', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_streams_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1.services.streams_service.transports.StreamsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_streams_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1.services.streams_service.transports.StreamsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamsServiceTransport() + adc.assert_called_once() + + +def test_streams_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + StreamsServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceGrpcAsyncIOTransport, + ], +) +def test_streams_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceGrpcAsyncIOTransport, + transports.StreamsServiceRestTransport, + ], +) +def test_streams_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.StreamsServiceGrpcTransport, grpc_helpers), + (transports.StreamsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_streams_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.StreamsServiceGrpcTransport, transports.StreamsServiceGrpcAsyncIOTransport]) +def test_streams_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_streams_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.StreamsServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_streams_service_rest_lro_client(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streams_service_host_no_port(transport_name): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streams_service_host_with_port(transport_name): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_streams_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = StreamsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = StreamsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_clusters._session + session2 = client2.transport.list_clusters._session + assert session1 != session2 + session1 = client1.transport.get_cluster._session + session2 = client2.transport.get_cluster._session + assert session1 != session2 + session1 = client1.transport.create_cluster._session + session2 = client2.transport.create_cluster._session + assert session1 != session2 + session1 = client1.transport.update_cluster._session + session2 = client2.transport.update_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_cluster._session + session2 = client2.transport.delete_cluster._session + assert session1 != session2 + session1 = client1.transport.list_streams._session + session2 = client2.transport.list_streams._session + assert session1 != session2 + session1 = client1.transport.get_stream._session + session2 = client2.transport.get_stream._session + assert session1 != session2 + session1 = client1.transport.create_stream._session + session2 = client2.transport.create_stream._session + assert session1 != session2 + session1 = client1.transport.update_stream._session + session2 = client2.transport.update_stream._session + assert session1 != session2 + session1 = client1.transport.delete_stream._session + session2 = client2.transport.delete_stream._session + assert session1 != session2 + session1 = client1.transport.get_stream_thumbnail._session + session2 = client2.transport.get_stream_thumbnail._session + assert session1 != session2 + session1 = client1.transport.generate_stream_hls_token._session + session2 = client2.transport.generate_stream_hls_token._session + assert session1 != session2 + session1 = client1.transport.list_events._session + session2 = client2.transport.list_events._session + assert session1 != session2 + session1 = client1.transport.get_event._session + session2 = client2.transport.get_event._session + assert session1 != session2 + session1 = client1.transport.create_event._session + session2 = client2.transport.create_event._session + assert session1 != session2 + session1 = client1.transport.update_event._session + session2 = client2.transport.update_event._session + assert session1 != session2 + session1 = client1.transport.delete_event._session + session2 = client2.transport.delete_event._session + assert session1 != session2 + session1 = client1.transport.list_series._session + session2 = client2.transport.list_series._session + assert session1 != session2 + session1 = client1.transport.get_series._session + session2 = client2.transport.get_series._session + assert session1 != session2 + session1 = client1.transport.create_series._session + session2 = client2.transport.create_series._session + assert session1 != session2 + session1 = client1.transport.update_series._session + session2 = client2.transport.update_series._session + assert session1 != session2 + session1 = client1.transport.delete_series._session + session2 = client2.transport.delete_series._session + assert session1 != session2 + session1 = client1.transport.materialize_channel._session + session2 = client2.transport.materialize_channel._session + assert session1 != session2 +def test_streams_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamsServiceGrpcTransport( + 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_streams_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamsServiceGrpcAsyncIOTransport( + 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.StreamsServiceGrpcTransport, transports.StreamsServiceGrpcAsyncIOTransport]) +def test_streams_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.StreamsServiceGrpcTransport, transports.StreamsServiceGrpcAsyncIOTransport]) +def test_streams_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_streams_service_grpc_lro_client(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_streams_service_grpc_lro_async_client(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_channel_path(): + project = "squid" + location = "clam" + cluster = "whelk" + channel = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/channels/{channel}".format(project=project, location=location, cluster=cluster, channel=channel, ) + actual = StreamsServiceClient.channel_path(project, location, cluster, channel) + assert expected == actual + + +def test_parse_channel_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "channel": "mussel", + } + path = StreamsServiceClient.channel_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_channel_path(path) + assert expected == actual + +def test_cluster_path(): + project = "winkle" + location = "nautilus" + cluster = "scallop" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = StreamsServiceClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "abalone", + "location": "squid", + "cluster": "clam", + } + path = StreamsServiceClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_cluster_path(path) + assert expected == actual + +def test_event_path(): + project = "whelk" + location = "octopus" + cluster = "oyster" + event = "nudibranch" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/events/{event}".format(project=project, location=location, cluster=cluster, event=event, ) + actual = StreamsServiceClient.event_path(project, location, cluster, event) + assert expected == actual + + +def test_parse_event_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "cluster": "winkle", + "event": "nautilus", + } + path = StreamsServiceClient.event_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_event_path(path) + assert expected == actual + +def test_series_path(): + project = "scallop" + location = "abalone" + cluster = "squid" + series = "clam" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + actual = StreamsServiceClient.series_path(project, location, cluster, series) + assert expected == actual + + +def test_parse_series_path(): + expected = { + "project": "whelk", + "location": "octopus", + "cluster": "oyster", + "series": "nudibranch", + } + path = StreamsServiceClient.series_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_series_path(path) + assert expected == actual + +def test_stream_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + stream = "nautilus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + actual = StreamsServiceClient.stream_path(project, location, cluster, stream) + assert expected == actual + + +def test_parse_stream_path(): + expected = { + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "stream": "clam", + } + path = StreamsServiceClient.stream_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_stream_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = StreamsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = StreamsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = StreamsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = StreamsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = StreamsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = StreamsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = StreamsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = StreamsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = StreamsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = StreamsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.StreamsServiceTransport, '_prep_wrapped_messages') as prep: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.StreamsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = StreamsServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_warehouse.py b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_warehouse.py new file mode 100644 index 000000000000..966bf4ffb04b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1/tests/unit/gapic/visionai_v1/test_warehouse.py @@ -0,0 +1,44347 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1.services.warehouse import WarehouseAsyncClient +from google.cloud.visionai_v1.services.warehouse import WarehouseClient +from google.cloud.visionai_v1.services.warehouse import pagers +from google.cloud.visionai_v1.services.warehouse import transports +from google.cloud.visionai_v1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 WarehouseClient._get_default_mtls_endpoint(None) is None + assert WarehouseClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WarehouseClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WarehouseClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WarehouseClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WarehouseClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert WarehouseClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WarehouseClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WarehouseClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WarehouseClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert WarehouseClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert WarehouseClient._get_client_cert_source(None, False) is None + assert WarehouseClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WarehouseClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert WarehouseClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WarehouseClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WarehouseClient._DEFAULT_UNIVERSE + default_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WarehouseClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WarehouseClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WarehouseClient.DEFAULT_MTLS_ENDPOINT + assert WarehouseClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WarehouseClient._get_api_endpoint(None, None, default_universe, "always") == WarehouseClient.DEFAULT_MTLS_ENDPOINT + assert WarehouseClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WarehouseClient.DEFAULT_MTLS_ENDPOINT + assert WarehouseClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WarehouseClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WarehouseClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert WarehouseClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WarehouseClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WarehouseClient._get_universe_domain(None, None) == WarehouseClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WarehouseClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc"), + (WarehouseClient, transports.WarehouseRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WarehouseClient, "grpc"), + (WarehouseAsyncClient, "grpc_asyncio"), + (WarehouseClient, "rest"), +]) +def test_warehouse_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WarehouseGrpcTransport, "grpc"), + (transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WarehouseRestTransport, "rest"), +]) +def test_warehouse_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WarehouseClient, "grpc"), + (WarehouseAsyncClient, "grpc_asyncio"), + (WarehouseClient, "rest"), +]) +def test_warehouse_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_warehouse_client_get_transport_class(): + transport = WarehouseClient.get_transport_class() + available_transports = [ + transports.WarehouseGrpcTransport, + transports.WarehouseRestTransport, + ] + assert transport in available_transports + + transport = WarehouseClient.get_transport_class("grpc") + assert transport == transports.WarehouseGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio"), + (WarehouseClient, transports.WarehouseRestTransport, "rest"), +]) +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +def test_warehouse_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(WarehouseClient, '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(WarehouseClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", "true"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", "false"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WarehouseClient, transports.WarehouseRestTransport, "rest", "true"), + (WarehouseClient, transports.WarehouseRestTransport, "rest", "false"), +]) +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_warehouse_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + WarehouseClient, WarehouseAsyncClient +]) +@mock.patch.object(WarehouseClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WarehouseAsyncClient)) +def test_warehouse_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + WarehouseClient, WarehouseAsyncClient +]) +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +def test_warehouse_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WarehouseClient._DEFAULT_UNIVERSE + default_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio"), + (WarehouseClient, transports.WarehouseRestTransport, "rest"), +]) +def test_warehouse_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", grpc_helpers), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WarehouseClient, transports.WarehouseRestTransport, "rest", None), +]) +def test_warehouse_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_warehouse_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1.services.warehouse.transports.WarehouseGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WarehouseClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", grpc_helpers), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_warehouse_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAssetRequest, + dict, +]) +def test_create_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset( + name='name_value', + ) + response = client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +def test_create_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAssetRequest() + + +def test_create_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateAssetRequest( + parent='parent_value', + asset_id='asset_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAssetRequest( + parent='parent_value', + asset_id='asset_id_value', + ) + +def test_create_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_asset] = mock_rpc + request = {} + client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.create_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAssetRequest() + +@pytest.mark.asyncio +async def test_create_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_asset] = mock_object + + request = {} + await client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_asset_async_from_dict(): + await test_create_asset_async(request_type=dict) + + +def test_create_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAssetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + call.return_value = warehouse.Asset() + client.create_asset(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_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAssetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + await client.create_asset(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_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_asset( + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].asset_id + mock_val = 'asset_id_value' + assert arg == mock_val + + +def test_create_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.CreateAssetRequest(), + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + +@pytest.mark.asyncio +async def test_create_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_asset( + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].asset_id + mock_val = 'asset_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.CreateAssetRequest(), + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAssetRequest, + dict, +]) +def test_update_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset( + name='name_value', + ) + response = client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +def test_update_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAssetRequest() + + +def test_update_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateAssetRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAssetRequest( + ) + +def test_update_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_asset] = mock_rpc + request = {} + client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.update_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAssetRequest() + +@pytest.mark.asyncio +async def test_update_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_asset] = mock_object + + request = {} + await client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_asset_async_from_dict(): + await test_update_asset_async(request_type=dict) + + +def test_update_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAssetRequest() + + request.asset.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + call.return_value = warehouse.Asset() + client.update_asset(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', + 'asset.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAssetRequest() + + request.asset.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + await client.update_asset(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', + 'asset.name=name_value', + ) in kw['metadata'] + + +def test_update_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_asset( + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.UpdateAssetRequest(), + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_asset( + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.UpdateAssetRequest(), + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAssetRequest, + dict, +]) +def test_get_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset( + name='name_value', + ) + response = client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +def test_get_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAssetRequest() + + +def test_get_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAssetRequest( + name='name_value', + ) + +def test_get_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_asset] = mock_rpc + request = {} + client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.get_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAssetRequest() + +@pytest.mark.asyncio +async def test_get_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_asset] = mock_object + + request = {} + await client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_asset_async_from_dict(): + await test_get_asset_async(request_type=dict) + + +def test_get_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + call.return_value = warehouse.Asset() + client.get_asset(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_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + await client.get_asset(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_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.GetAssetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.GetAssetRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_assets_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 = WarehouseClient( + 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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListAssetsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAssetsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListAssetsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = warehouse.ListAssetsResponse() + client.list_assets(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_assets_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse()) + await client.list_assets(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_assets_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_assets_flattened_error(): + client = WarehouseClient( + 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_assets( + warehouse.ListAssetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_assets_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_assets_flattened_error_async(): + client = WarehouseAsyncClient( + 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_assets( + warehouse.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Asset) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Asset) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAssetRequest, + dict, +]) +def test_delete_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAssetRequest() + + +def test_delete_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAssetRequest( + name='name_value', + ) + +def test_delete_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_asset] = mock_rpc + request = {} + client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAssetRequest() + +@pytest.mark.asyncio +async def test_delete_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_asset] = mock_object + + request = {} + await client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_asset_async_from_dict(): + await test_delete_asset_async(request_type=dict) + + +def test_delete_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_asset(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_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_asset(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_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.DeleteAssetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.DeleteAssetRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UploadAssetRequest, + dict, +]) +def test_upload_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.upload_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UploadAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_upload_asset_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 = WarehouseClient( + 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.upload_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.upload_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UploadAssetRequest() + + +def test_upload_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UploadAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.upload_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UploadAssetRequest( + name='name_value', + ) + +def test_upload_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.upload_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.upload_asset] = mock_rpc + request = {} + client.upload_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.upload_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_upload_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.upload_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UploadAssetRequest() + +@pytest.mark.asyncio +async def test_upload_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.upload_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.upload_asset] = mock_object + + request = {} + await client.upload_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.upload_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_upload_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.UploadAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.upload_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UploadAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_upload_asset_async_from_dict(): + await test_upload_asset_async(request_type=dict) + + +def test_upload_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UploadAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_asset), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.upload_asset(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_upload_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UploadAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.upload_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.GenerateRetrievalUrlRequest, + dict, +]) +def test_generate_retrieval_url(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_retrieval_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.GenerateRetrievalUrlResponse( + signed_uri='signed_uri_value', + ) + response = client.generate_retrieval_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GenerateRetrievalUrlRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateRetrievalUrlResponse) + assert response.signed_uri == 'signed_uri_value' + + +def test_generate_retrieval_url_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_retrieval_url), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_retrieval_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateRetrievalUrlRequest() + + +def test_generate_retrieval_url_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GenerateRetrievalUrlRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_retrieval_url), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_retrieval_url(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateRetrievalUrlRequest( + name='name_value', + ) + +def test_generate_retrieval_url_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_retrieval_url in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_retrieval_url] = mock_rpc + request = {} + client.generate_retrieval_url(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_retrieval_url(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_retrieval_url_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_retrieval_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateRetrievalUrlResponse( + signed_uri='signed_uri_value', + )) + response = await client.generate_retrieval_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateRetrievalUrlRequest() + +@pytest.mark.asyncio +async def test_generate_retrieval_url_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_retrieval_url in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.generate_retrieval_url] = mock_object + + request = {} + await client.generate_retrieval_url(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.generate_retrieval_url(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_retrieval_url_async(transport: str = 'grpc_asyncio', request_type=warehouse.GenerateRetrievalUrlRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_retrieval_url), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateRetrievalUrlResponse( + signed_uri='signed_uri_value', + )) + response = await client.generate_retrieval_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GenerateRetrievalUrlRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateRetrievalUrlResponse) + assert response.signed_uri == 'signed_uri_value' + + +@pytest.mark.asyncio +async def test_generate_retrieval_url_async_from_dict(): + await test_generate_retrieval_url_async(request_type=dict) + + +def test_generate_retrieval_url_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GenerateRetrievalUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_retrieval_url), + '__call__') as call: + call.return_value = warehouse.GenerateRetrievalUrlResponse() + client.generate_retrieval_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_retrieval_url_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GenerateRetrievalUrlRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_retrieval_url), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateRetrievalUrlResponse()) + await client.generate_retrieval_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.AnalyzeAssetRequest, + dict, +]) +def test_analyze_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.analyze_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.AnalyzeAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_analyze_asset_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 = WarehouseClient( + 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.analyze_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.analyze_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AnalyzeAssetRequest() + + +def test_analyze_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.AnalyzeAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.analyze_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AnalyzeAssetRequest( + name='name_value', + ) + +def test_analyze_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.analyze_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.analyze_asset] = mock_rpc + request = {} + client.analyze_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.analyze_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_analyze_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.analyze_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AnalyzeAssetRequest() + +@pytest.mark.asyncio +async def test_analyze_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.analyze_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.analyze_asset] = mock_object + + request = {} + await client.analyze_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.analyze_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_analyze_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.AnalyzeAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.analyze_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.AnalyzeAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_analyze_asset_async_from_dict(): + await test_analyze_asset_async(request_type=dict) + + +def test_analyze_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.AnalyzeAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_asset), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.analyze_asset(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_analyze_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.AnalyzeAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.analyze_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.IndexAssetRequest, + dict, +]) +def test_index_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.index_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.IndexAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_index_asset_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 = WarehouseClient( + 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.index_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.index_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.IndexAssetRequest() + + +def test_index_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.IndexAssetRequest( + name='name_value', + index='index_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.index_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.index_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.IndexAssetRequest( + name='name_value', + index='index_value', + ) + +def test_index_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.index_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.index_asset] = mock_rpc + request = {} + client.index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.index_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_index_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.index_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.index_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.IndexAssetRequest() + +@pytest.mark.asyncio +async def test_index_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.index_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.index_asset] = mock_object + + request = {} + await client.index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.index_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_index_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.IndexAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.index_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.IndexAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_index_asset_async_from_dict(): + await test_index_asset_async(request_type=dict) + + +def test_index_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.IndexAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.index_asset), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.index_asset(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_index_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.IndexAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.index_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.RemoveIndexAssetRequest, + dict, +]) +def test_remove_index_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_index_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.RemoveIndexAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_index_asset_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 = WarehouseClient( + 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.remove_index_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_index_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.RemoveIndexAssetRequest() + + +def test_remove_index_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.RemoveIndexAssetRequest( + name='name_value', + index='index_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_index_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_index_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.RemoveIndexAssetRequest( + name='name_value', + index='index_value', + ) + +def test_remove_index_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_index_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_index_asset] = mock_rpc + request = {} + client.remove_index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_index_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_index_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_index_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.remove_index_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.RemoveIndexAssetRequest() + +@pytest.mark.asyncio +async def test_remove_index_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.remove_index_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.remove_index_asset] = mock_object + + request = {} + await client.remove_index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.remove_index_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_index_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.RemoveIndexAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_index_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.remove_index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.RemoveIndexAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_index_asset_async_from_dict(): + await test_remove_index_asset_async(request_type=dict) + + +def test_remove_index_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.RemoveIndexAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_index_asset), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_index_asset(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_remove_index_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.RemoveIndexAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_index_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.ViewIndexedAssetsRequest, + dict, +]) +def test_view_indexed_assets(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ViewIndexedAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.view_indexed_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ViewIndexedAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ViewIndexedAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_view_indexed_assets_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 = WarehouseClient( + 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.view_indexed_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.view_indexed_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ViewIndexedAssetsRequest() + + +def test_view_indexed_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ViewIndexedAssetsRequest( + index='index_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.view_indexed_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ViewIndexedAssetsRequest( + index='index_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_view_indexed_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.view_indexed_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.view_indexed_assets] = mock_rpc + request = {} + client.view_indexed_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.view_indexed_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_view_indexed_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewIndexedAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.view_indexed_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ViewIndexedAssetsRequest() + +@pytest.mark.asyncio +async def test_view_indexed_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.view_indexed_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.view_indexed_assets] = mock_object + + request = {} + await client.view_indexed_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.view_indexed_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_view_indexed_assets_async(transport: str = 'grpc_asyncio', request_type=warehouse.ViewIndexedAssetsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewIndexedAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.view_indexed_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ViewIndexedAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ViewIndexedAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_view_indexed_assets_async_from_dict(): + await test_view_indexed_assets_async(request_type=dict) + + +def test_view_indexed_assets_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ViewIndexedAssetsRequest() + + request.index = 'index_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + call.return_value = warehouse.ViewIndexedAssetsResponse() + client.view_indexed_assets(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', + 'index=index_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_view_indexed_assets_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ViewIndexedAssetsRequest() + + request.index = 'index_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewIndexedAssetsResponse()) + await client.view_indexed_assets(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', + 'index=index_value', + ) in kw['metadata'] + + +def test_view_indexed_assets_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ViewIndexedAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.view_indexed_assets( + index='index_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].index + mock_val = 'index_value' + assert arg == mock_val + + +def test_view_indexed_assets_flattened_error(): + client = WarehouseClient( + 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.view_indexed_assets( + warehouse.ViewIndexedAssetsRequest(), + index='index_value', + ) + +@pytest.mark.asyncio +async def test_view_indexed_assets_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ViewIndexedAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewIndexedAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.view_indexed_assets( + index='index_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].index + mock_val = 'index_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_view_indexed_assets_flattened_error_async(): + client = WarehouseAsyncClient( + 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.view_indexed_assets( + warehouse.ViewIndexedAssetsRequest(), + index='index_value', + ) + + +def test_view_indexed_assets_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + next_page_token='abc', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[], + next_page_token='def', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + ], + next_page_token='ghi', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('index', ''), + )), + ) + pager = client.view_indexed_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.IndexedAsset) + for i in results) +def test_view_indexed_assets_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + next_page_token='abc', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[], + next_page_token='def', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + ], + next_page_token='ghi', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + ), + RuntimeError, + ) + pages = list(client.view_indexed_assets(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_view_indexed_assets_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + next_page_token='abc', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[], + next_page_token='def', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + ], + next_page_token='ghi', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + ), + RuntimeError, + ) + async_pager = await client.view_indexed_assets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.IndexedAsset) + for i in responses) + + +@pytest.mark.asyncio +async def test_view_indexed_assets_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_indexed_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + next_page_token='abc', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[], + next_page_token='def', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + ], + next_page_token='ghi', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.view_indexed_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateIndexRequest, + dict, +]) +def test_create_index(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_index_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 = WarehouseClient( + 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_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateIndexRequest() + + +def test_create_index_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateIndexRequest( + parent='parent_value', + index_id='index_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_index(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateIndexRequest( + parent='parent_value', + index_id='index_id_value', + ) + +def test_create_index_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_index] = mock_rpc + request = {} + client.create_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_index_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateIndexRequest() + +@pytest.mark.asyncio +async def test_create_index_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_index in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_index] = mock_object + + request = {} + await client.create_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_index_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateIndexRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_index_async_from_dict(): + await test_create_index_async(request_type=dict) + + +def test_create_index_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateIndexRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_index(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_index_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateIndexRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_index(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_index_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_index( + parent='parent_value', + index=warehouse.Index(entire_corpus=True), + index_id='index_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].index + mock_val = warehouse.Index(entire_corpus=True) + assert arg == mock_val + arg = args[0].index_id + mock_val = 'index_id_value' + assert arg == mock_val + + +def test_create_index_flattened_error(): + client = WarehouseClient( + 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_index( + warehouse.CreateIndexRequest(), + parent='parent_value', + index=warehouse.Index(entire_corpus=True), + index_id='index_id_value', + ) + +@pytest.mark.asyncio +async def test_create_index_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_index( + parent='parent_value', + index=warehouse.Index(entire_corpus=True), + index_id='index_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].index + mock_val = warehouse.Index(entire_corpus=True) + assert arg == mock_val + arg = args[0].index_id + mock_val = 'index_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_index_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index( + warehouse.CreateIndexRequest(), + parent='parent_value', + index=warehouse.Index(entire_corpus=True), + index_id='index_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateIndexRequest, + dict, +]) +def test_update_index(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_index_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 = WarehouseClient( + 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_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateIndexRequest() + + +def test_update_index_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateIndexRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_index(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateIndexRequest( + ) + +def test_update_index_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_index] = mock_rpc + request = {} + client.update_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_index_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateIndexRequest() + +@pytest.mark.asyncio +async def test_update_index_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_index in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_index] = mock_object + + request = {} + await client.update_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_index_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateIndexRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_index_async_from_dict(): + await test_update_index_async(request_type=dict) + + +def test_update_index_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateIndexRequest() + + request.index.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_index(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', + 'index.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_index_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateIndexRequest() + + request.index.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_index(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', + 'index.name=name_value', + ) in kw['metadata'] + + +def test_update_index_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_index( + index=warehouse.Index(entire_corpus=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].index + mock_val = warehouse.Index(entire_corpus=True) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_index_flattened_error(): + client = WarehouseClient( + 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_index( + warehouse.UpdateIndexRequest(), + index=warehouse.Index(entire_corpus=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_index_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_index( + index=warehouse.Index(entire_corpus=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].index + mock_val = warehouse.Index(entire_corpus=True) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_index_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index( + warehouse.UpdateIndexRequest(), + index=warehouse.Index(entire_corpus=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetIndexRequest, + dict, +]) +def test_get_index(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Index( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.Index.State.CREATING, + entire_corpus=True, + ) + response = client.get_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Index) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == warehouse.Index.State.CREATING + + +def test_get_index_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 = WarehouseClient( + 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_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetIndexRequest() + + +def test_get_index_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetIndexRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_index(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetIndexRequest( + name='name_value', + ) + +def test_get_index_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_index] = mock_rpc + request = {} + client.get_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_index_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Index( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.Index.State.CREATING, + )) + response = await client.get_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetIndexRequest() + +@pytest.mark.asyncio +async def test_get_index_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_index in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_index] = mock_object + + request = {} + await client.get_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_index_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetIndexRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Index( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.Index.State.CREATING, + )) + response = await client.get_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Index) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == warehouse.Index.State.CREATING + + +@pytest.mark.asyncio +async def test_get_index_async_from_dict(): + await test_get_index_async(request_type=dict) + + +def test_get_index_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetIndexRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index), + '__call__') as call: + call.return_value = warehouse.Index() + client.get_index(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_index_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetIndexRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Index()) + await client.get_index(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_index_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Index() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_index( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_index_flattened_error(): + client = WarehouseClient( + 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_index( + warehouse.GetIndexRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_index_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Index() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Index()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_index( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_index_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index( + warehouse.GetIndexRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListIndexesRequest, + dict, +]) +def test_list_indexes(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_indexes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListIndexesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_indexes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListIndexesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIndexesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_indexes_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 = WarehouseClient( + 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_indexes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_indexes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListIndexesRequest() + + +def test_list_indexes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListIndexesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_indexes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListIndexesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_indexes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_indexes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_indexes] = mock_rpc + request = {} + client.list_indexes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_indexes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_indexes_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_indexes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListIndexesRequest() + +@pytest.mark.asyncio +async def test_list_indexes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_indexes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_indexes] = mock_object + + request = {} + await client.list_indexes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_indexes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_indexes_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListIndexesRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_indexes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_indexes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListIndexesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIndexesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_indexes_async_from_dict(): + await test_list_indexes_async(request_type=dict) + + +def test_list_indexes_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListIndexesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + call.return_value = warehouse.ListIndexesResponse() + client.list_indexes(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_indexes_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListIndexesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexesResponse()) + await client.list_indexes(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_indexes_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListIndexesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_indexes( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_indexes_flattened_error(): + client = WarehouseClient( + 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_indexes( + warehouse.ListIndexesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_indexes_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListIndexesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_indexes( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_indexes_flattened_error_async(): + client = WarehouseAsyncClient( + 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_indexes( + warehouse.ListIndexesRequest(), + parent='parent_value', + ) + + +def test_list_indexes_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + warehouse.Index(), + ], + next_page_token='abc', + ), + warehouse.ListIndexesResponse( + indexes=[], + next_page_token='def', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_indexes(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Index) + for i in results) +def test_list_indexes_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + warehouse.Index(), + ], + next_page_token='abc', + ), + warehouse.ListIndexesResponse( + indexes=[], + next_page_token='def', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + ], + ), + RuntimeError, + ) + pages = list(client.list_indexes(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_indexes_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + warehouse.Index(), + ], + next_page_token='abc', + ), + warehouse.ListIndexesResponse( + indexes=[], + next_page_token='def', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_indexes(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Index) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_indexes_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_indexes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + warehouse.Index(), + ], + next_page_token='abc', + ), + warehouse.ListIndexesResponse( + indexes=[], + next_page_token='def', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_indexes(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteIndexRequest, + dict, +]) +def test_delete_index(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_index_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 = WarehouseClient( + 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_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteIndexRequest() + + +def test_delete_index_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteIndexRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_index(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteIndexRequest( + name='name_value', + ) + +def test_delete_index_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_index] = mock_rpc + request = {} + client.delete_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_index_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteIndexRequest() + +@pytest.mark.asyncio +async def test_delete_index_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_index in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_index] = mock_object + + request = {} + await client.delete_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_index_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteIndexRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_index_async_from_dict(): + await test_delete_index_async(request_type=dict) + + +def test_delete_index_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteIndexRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_index(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_index_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteIndexRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_index(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_index_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_index( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_index_flattened_error(): + client = WarehouseClient( + 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_index( + warehouse.DeleteIndexRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_index_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_index( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_index_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index( + warehouse.DeleteIndexRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateCorpusRequest, + dict, +]) +def test_create_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCorpusRequest() + + +def test_create_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateCorpusRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCorpusRequest( + parent='parent_value', + ) + +def test_create_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_corpus] = mock_rpc + request = {} + client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCorpusRequest() + +@pytest.mark.asyncio +async def test_create_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_corpus] = mock_object + + request = {} + await client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_corpus_async_from_dict(): + await test_create_corpus_async(request_type=dict) + + +def test_create_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateCorpusRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_corpus(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_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateCorpusRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_corpus(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_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_corpus( + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + + +def test_create_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.CreateCorpusRequest(), + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_corpus( + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.CreateCorpusRequest(), + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetCorpusRequest, + dict, +]) +def test_get_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + ) + response = client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.type_ == warehouse.Corpus.Type.STREAM_VIDEO + + +def test_get_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCorpusRequest() + + +def test_get_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetCorpusRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCorpusRequest( + name='name_value', + ) + +def test_get_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_corpus] = mock_rpc + request = {} + client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + )) + response = await client.get_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCorpusRequest() + +@pytest.mark.asyncio +async def test_get_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_corpus] = mock_object + + request = {} + await client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + )) + response = await client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.type_ == warehouse.Corpus.Type.STREAM_VIDEO + + +@pytest.mark.asyncio +async def test_get_corpus_async_from_dict(): + await test_get_corpus_async(request_type=dict) + + +def test_get_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + call.return_value = warehouse.Corpus() + client.get_corpus(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_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + await client.get_corpus(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_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.GetCorpusRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.GetCorpusRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateCorpusRequest, + dict, +]) +def test_update_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + ) + response = client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.type_ == warehouse.Corpus.Type.STREAM_VIDEO + + +def test_update_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCorpusRequest() + + +def test_update_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateCorpusRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCorpusRequest( + ) + +def test_update_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_corpus] = mock_rpc + request = {} + client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + )) + response = await client.update_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCorpusRequest() + +@pytest.mark.asyncio +async def test_update_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_corpus] = mock_object + + request = {} + await client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + )) + response = await client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.type_ == warehouse.Corpus.Type.STREAM_VIDEO + + +@pytest.mark.asyncio +async def test_update_corpus_async_from_dict(): + await test_update_corpus_async(request_type=dict) + + +def test_update_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateCorpusRequest() + + request.corpus.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + call.return_value = warehouse.Corpus() + client.update_corpus(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', + 'corpus.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateCorpusRequest() + + request.corpus.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + await client.update_corpus(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', + 'corpus.name=name_value', + ) in kw['metadata'] + + +def test_update_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_corpus( + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.UpdateCorpusRequest(), + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_corpus( + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.UpdateCorpusRequest(), + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListCorporaRequest, + dict, +]) +def test_list_corpora(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + ) + response = client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListCorporaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCorporaPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_corpora_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 = WarehouseClient( + 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_corpora), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_corpora() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCorporaRequest() + + +def test_list_corpora_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListCorporaRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_corpora(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCorporaRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_corpora_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_corpora in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_corpora] = mock_rpc + request = {} + client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_corpora(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_corpora_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_corpora() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCorporaRequest() + +@pytest.mark.asyncio +async def test_list_corpora_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_corpora in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_corpora] = mock_object + + request = {} + await client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_corpora(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_corpora_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListCorporaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListCorporaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCorporaAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_corpora_async_from_dict(): + await test_list_corpora_async(request_type=dict) + + +def test_list_corpora_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListCorporaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + call.return_value = warehouse.ListCorporaResponse() + client.list_corpora(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_corpora_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListCorporaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse()) + await client.list_corpora(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_corpora_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCorporaResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_corpora( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_corpora_flattened_error(): + client = WarehouseClient( + 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_corpora( + warehouse.ListCorporaRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_corpora_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCorporaResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_corpora( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_corpora_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpora( + warehouse.ListCorporaRequest(), + parent='parent_value', + ) + + +def test_list_corpora_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_corpora(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Corpus) + for i in results) +def test_list_corpora_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + pages = list(client.list_corpora(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_corpora_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_corpora(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Corpus) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_corpora_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_corpora(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteCorpusRequest, + dict, +]) +def test_delete_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCorpusRequest() + + +def test_delete_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteCorpusRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCorpusRequest( + name='name_value', + ) + +def test_delete_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_corpus] = mock_rpc + request = {} + client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCorpusRequest() + +@pytest.mark.asyncio +async def test_delete_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_corpus] = mock_object + + request = {} + await client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_corpus_async_from_dict(): + await test_delete_corpus_async(request_type=dict) + + +def test_delete_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + call.return_value = None + client.delete_corpus(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_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_corpus(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_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__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_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.DeleteCorpusRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__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_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.DeleteCorpusRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.AnalyzeCorpusRequest, + dict, +]) +def test_analyze_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.analyze_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.AnalyzeCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_analyze_corpus_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 = WarehouseClient( + 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.analyze_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.analyze_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AnalyzeCorpusRequest() + + +def test_analyze_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.AnalyzeCorpusRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.analyze_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AnalyzeCorpusRequest( + name='name_value', + ) + +def test_analyze_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.analyze_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.analyze_corpus] = mock_rpc + request = {} + client.analyze_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.analyze_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_analyze_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.analyze_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AnalyzeCorpusRequest() + +@pytest.mark.asyncio +async def test_analyze_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.analyze_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.analyze_corpus] = mock_object + + request = {} + await client.analyze_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.analyze_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_analyze_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.AnalyzeCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.analyze_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.AnalyzeCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_analyze_corpus_async_from_dict(): + await test_analyze_corpus_async(request_type=dict) + + +def test_analyze_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.AnalyzeCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_corpus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.analyze_corpus(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_analyze_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.AnalyzeCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.analyze_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateDataSchemaRequest, + dict, +]) +def test_create_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + response = client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +def test_create_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateDataSchemaRequest() + + +def test_create_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateDataSchemaRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateDataSchemaRequest( + parent='parent_value', + ) + +def test_create_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_schema] = mock_rpc + request = {} + client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.create_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateDataSchemaRequest() + +@pytest.mark.asyncio +async def test_create_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_data_schema] = mock_object + + request = {} + await client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +@pytest.mark.asyncio +async def test_create_data_schema_async_from_dict(): + await test_create_data_schema_async(request_type=dict) + + +def test_create_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateDataSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + call.return_value = warehouse.DataSchema() + client.create_data_schema(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_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateDataSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + await client.create_data_schema(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_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_data_schema( + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + + +def test_create_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.CreateDataSchemaRequest(), + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_data_schema( + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.CreateDataSchemaRequest(), + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateDataSchemaRequest, + dict, +]) +def test_update_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + response = client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +def test_update_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateDataSchemaRequest() + + +def test_update_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateDataSchemaRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateDataSchemaRequest( + ) + +def test_update_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_schema] = mock_rpc + request = {} + client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.update_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateDataSchemaRequest() + +@pytest.mark.asyncio +async def test_update_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_data_schema] = mock_object + + request = {} + await client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +@pytest.mark.asyncio +async def test_update_data_schema_async_from_dict(): + await test_update_data_schema_async(request_type=dict) + + +def test_update_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateDataSchemaRequest() + + request.data_schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + call.return_value = warehouse.DataSchema() + client.update_data_schema(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', + 'data_schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateDataSchemaRequest() + + request.data_schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + await client.update_data_schema(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', + 'data_schema.name=name_value', + ) in kw['metadata'] + + +def test_update_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_schema( + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.UpdateDataSchemaRequest(), + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_schema( + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.UpdateDataSchemaRequest(), + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetDataSchemaRequest, + dict, +]) +def test_get_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + response = client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +def test_get_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetDataSchemaRequest() + + +def test_get_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetDataSchemaRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetDataSchemaRequest( + name='name_value', + ) + +def test_get_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_schema] = mock_rpc + request = {} + client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.get_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetDataSchemaRequest() + +@pytest.mark.asyncio +async def test_get_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_schema] = mock_object + + request = {} + await client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +@pytest.mark.asyncio +async def test_get_data_schema_async_from_dict(): + await test_get_data_schema_async(request_type=dict) + + +def test_get_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + call.return_value = warehouse.DataSchema() + client.get_data_schema(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_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + await client.get_data_schema(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_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.GetDataSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.GetDataSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteDataSchemaRequest, + dict, +]) +def test_delete_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteDataSchemaRequest() + + +def test_delete_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteDataSchemaRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteDataSchemaRequest( + name='name_value', + ) + +def test_delete_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_schema] = mock_rpc + request = {} + client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteDataSchemaRequest() + +@pytest.mark.asyncio +async def test_delete_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_data_schema] = mock_object + + request = {} + await client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_data_schema_async_from_dict(): + await test_delete_data_schema_async(request_type=dict) + + +def test_delete_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + call.return_value = None + client.delete_data_schema(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_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_data_schema(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_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__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_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.DeleteDataSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__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_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.DeleteDataSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListDataSchemasRequest, + dict, +]) +def test_list_data_schemas(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListDataSchemasRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_schemas_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 = WarehouseClient( + 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_data_schemas), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListDataSchemasRequest() + + +def test_list_data_schemas_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListDataSchemasRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_schemas(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListDataSchemasRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_data_schemas_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_schemas in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_schemas] = mock_rpc + request = {} + client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_schemas_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListDataSchemasRequest() + +@pytest.mark.asyncio +async def test_list_data_schemas_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_data_schemas in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_data_schemas] = mock_object + + request = {} + await client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_data_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_schemas_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListDataSchemasRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListDataSchemasRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSchemasAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_schemas_async_from_dict(): + await test_list_data_schemas_async(request_type=dict) + + +def test_list_data_schemas_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListDataSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + call.return_value = warehouse.ListDataSchemasResponse() + client.list_data_schemas(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_data_schemas_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListDataSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse()) + await client.list_data_schemas(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_data_schemas_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListDataSchemasResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_data_schemas_flattened_error(): + client = WarehouseClient( + 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_data_schemas( + warehouse.ListDataSchemasRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_data_schemas_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListDataSchemasResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_data_schemas_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schemas( + warehouse.ListDataSchemasRequest(), + parent='parent_value', + ) + + +def test_list_data_schemas_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_schemas(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.DataSchema) + for i in results) +def test_list_data_schemas_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_schemas(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_data_schemas_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_schemas(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.DataSchema) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_schemas_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_data_schemas(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAnnotationRequest, + dict, +]) +def test_create_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation( + name='name_value', + ) + response = client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +def test_create_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAnnotationRequest() + + +def test_create_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateAnnotationRequest( + parent='parent_value', + annotation_id='annotation_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAnnotationRequest( + parent='parent_value', + annotation_id='annotation_id_value', + ) + +def test_create_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_annotation] = mock_rpc + request = {} + client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.create_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAnnotationRequest() + +@pytest.mark.asyncio +async def test_create_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_annotation] = mock_object + + request = {} + await client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_annotation_async_from_dict(): + await test_create_annotation_async(request_type=dict) + + +def test_create_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAnnotationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + call.return_value = warehouse.Annotation() + client.create_annotation(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_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAnnotationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + await client.create_annotation(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_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_annotation( + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].annotation_id + mock_val = 'annotation_id_value' + assert arg == mock_val + + +def test_create_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.CreateAnnotationRequest(), + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_annotation( + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].annotation_id + mock_val = 'annotation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.CreateAnnotationRequest(), + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAnnotationRequest, + dict, +]) +def test_get_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation( + name='name_value', + ) + response = client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +def test_get_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAnnotationRequest() + + +def test_get_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetAnnotationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAnnotationRequest( + name='name_value', + ) + +def test_get_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_annotation] = mock_rpc + request = {} + client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.get_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAnnotationRequest() + +@pytest.mark.asyncio +async def test_get_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_annotation] = mock_object + + request = {} + await client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_annotation_async_from_dict(): + await test_get_annotation_async(request_type=dict) + + +def test_get_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + call.return_value = warehouse.Annotation() + client.get_annotation(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_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + await client.get_annotation(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_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.GetAnnotationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.GetAnnotationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAnnotationsRequest, + dict, +]) +def test_list_annotations(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListAnnotationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_annotations_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 = WarehouseClient( + 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_annotations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_annotations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAnnotationsRequest() + + +def test_list_annotations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListAnnotationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_annotations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAnnotationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_annotations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_annotations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_annotations] = mock_rpc + request = {} + client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_annotations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_annotations_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_annotations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAnnotationsRequest() + +@pytest.mark.asyncio +async def test_list_annotations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_annotations in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_annotations] = mock_object + + request = {} + await client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_annotations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_annotations_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListAnnotationsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListAnnotationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_annotations_async_from_dict(): + await test_list_annotations_async(request_type=dict) + + +def test_list_annotations_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAnnotationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + call.return_value = warehouse.ListAnnotationsResponse() + client.list_annotations(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_annotations_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAnnotationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse()) + await client.list_annotations(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_annotations_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAnnotationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_annotations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_annotations_flattened_error(): + client = WarehouseClient( + 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_annotations( + warehouse.ListAnnotationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_annotations_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAnnotationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_annotations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_annotations_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotations( + warehouse.ListAnnotationsRequest(), + parent='parent_value', + ) + + +def test_list_annotations_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_annotations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Annotation) + for i in results) +def test_list_annotations_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_annotations(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_annotations_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_annotations(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Annotation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_annotations_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_annotations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAnnotationRequest, + dict, +]) +def test_update_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation( + name='name_value', + ) + response = client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +def test_update_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAnnotationRequest() + + +def test_update_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateAnnotationRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAnnotationRequest( + ) + +def test_update_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_annotation] = mock_rpc + request = {} + client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.update_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAnnotationRequest() + +@pytest.mark.asyncio +async def test_update_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_annotation] = mock_object + + request = {} + await client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_annotation_async_from_dict(): + await test_update_annotation_async(request_type=dict) + + +def test_update_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAnnotationRequest() + + request.annotation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + call.return_value = warehouse.Annotation() + client.update_annotation(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', + 'annotation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAnnotationRequest() + + request.annotation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + await client.update_annotation(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', + 'annotation.name=name_value', + ) in kw['metadata'] + + +def test_update_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_annotation( + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.UpdateAnnotationRequest(), + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_annotation( + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.UpdateAnnotationRequest(), + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAnnotationRequest, + dict, +]) +def test_delete_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAnnotationRequest() + + +def test_delete_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteAnnotationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAnnotationRequest( + name='name_value', + ) + +def test_delete_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_annotation] = mock_rpc + request = {} + client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAnnotationRequest() + +@pytest.mark.asyncio +async def test_delete_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_annotation] = mock_object + + request = {} + await client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_annotation_async_from_dict(): + await test_delete_annotation_async(request_type=dict) + + +def test_delete_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + call.return_value = None + client.delete_annotation(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_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_annotation(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_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__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_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.DeleteAnnotationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__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_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.DeleteAnnotationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.IngestAssetRequest, + dict, +]) +def test_ingest_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.ingest_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([warehouse.IngestAssetResponse()]) + response = client.ingest_asset(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, warehouse.IngestAssetResponse) + + +def test_ingest_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.ingest_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.ingest_asset] = mock_rpc + request = [{}] + client.ingest_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.ingest_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_ingest_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.ingest_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.ingest_asset] = mock_object + + request = [{}] + await client.ingest_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.ingest_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_ingest_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.IngestAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.ingest_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[warehouse.IngestAssetResponse()]) + response = await client.ingest_asset(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, warehouse.IngestAssetResponse) + + +@pytest.mark.asyncio +async def test_ingest_asset_async_from_dict(): + await test_ingest_asset_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ClipAssetRequest, + dict, +]) +def test_clip_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ClipAssetResponse( + ) + response = client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ClipAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.ClipAssetResponse) + + +def test_clip_asset_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 = WarehouseClient( + 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.clip_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.clip_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ClipAssetRequest() + + +def test_clip_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ClipAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.clip_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ClipAssetRequest( + name='name_value', + ) + +def test_clip_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clip_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clip_asset] = mock_rpc + request = {} + client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.clip_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_clip_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ClipAssetResponse( + )) + response = await client.clip_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ClipAssetRequest() + +@pytest.mark.asyncio +async def test_clip_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.clip_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.clip_asset] = mock_object + + request = {} + await client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.clip_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_clip_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.ClipAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ClipAssetResponse( + )) + response = await client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ClipAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.ClipAssetResponse) + + +@pytest.mark.asyncio +async def test_clip_asset_async_from_dict(): + await test_clip_asset_async(request_type=dict) + + +def test_clip_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ClipAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + call.return_value = warehouse.ClipAssetResponse() + client.clip_asset(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_clip_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ClipAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ClipAssetResponse()) + await client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.GenerateHlsUriRequest, + dict, +]) +def test_generate_hls_uri(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.GenerateHlsUriResponse( + uri='uri_value', + ) + response = client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GenerateHlsUriRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateHlsUriResponse) + assert response.uri == 'uri_value' + + +def test_generate_hls_uri_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 = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_hls_uri() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateHlsUriRequest() + + +def test_generate_hls_uri_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GenerateHlsUriRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_hls_uri(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateHlsUriRequest( + name='name_value', + ) + +def test_generate_hls_uri_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_hls_uri in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_hls_uri] = mock_rpc + request = {} + client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_hls_uri(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_hls_uri_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateHlsUriResponse( + uri='uri_value', + )) + response = await client.generate_hls_uri() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateHlsUriRequest() + +@pytest.mark.asyncio +async def test_generate_hls_uri_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_hls_uri in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.generate_hls_uri] = mock_object + + request = {} + await client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.generate_hls_uri(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_hls_uri_async(transport: str = 'grpc_asyncio', request_type=warehouse.GenerateHlsUriRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateHlsUriResponse( + uri='uri_value', + )) + response = await client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GenerateHlsUriRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateHlsUriResponse) + assert response.uri == 'uri_value' + + +@pytest.mark.asyncio +async def test_generate_hls_uri_async_from_dict(): + await test_generate_hls_uri_async(request_type=dict) + + +def test_generate_hls_uri_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GenerateHlsUriRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value = warehouse.GenerateHlsUriResponse() + client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_hls_uri_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GenerateHlsUriRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateHlsUriResponse()) + await client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.ImportAssetsRequest, + dict, +]) +def test_import_assets(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ImportAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_assets_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 = WarehouseClient( + 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.import_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.import_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ImportAssetsRequest() + + +def test_import_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ImportAssetsRequest( + assets_gcs_uri='assets_gcs_uri_value', + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.import_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ImportAssetsRequest( + assets_gcs_uri='assets_gcs_uri_value', + parent='parent_value', + ) + +def test_import_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_assets] = mock_rpc + request = {} + client.import_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_import_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ImportAssetsRequest() + +@pytest.mark.asyncio +async def test_import_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.import_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.import_assets] = mock_object + + request = {} + await client.import_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_import_assets_async(transport: str = 'grpc_asyncio', request_type=warehouse.ImportAssetsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ImportAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_assets_async_from_dict(): + await test_import_assets_async(request_type=dict) + + +def test_import_assets_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ImportAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_assets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_assets(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_import_assets_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ImportAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateSearchConfigRequest, + dict, +]) +def test_create_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig( + name='name_value', + ) + response = client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +def test_create_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchConfigRequest() + + +def test_create_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateSearchConfigRequest( + parent='parent_value', + search_config_id='search_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchConfigRequest( + parent='parent_value', + search_config_id='search_config_id_value', + ) + +def test_create_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_config] = mock_rpc + request = {} + client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.create_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchConfigRequest() + +@pytest.mark.asyncio +async def test_create_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_search_config] = mock_object + + request = {} + await client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_search_config_async_from_dict(): + await test_create_search_config_async(request_type=dict) + + +def test_create_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateSearchConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + call.return_value = warehouse.SearchConfig() + client.create_search_config(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_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateSearchConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + await client.create_search_config(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_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_search_config( + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].search_config_id + mock_val = 'search_config_id_value' + assert arg == mock_val + + +def test_create_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.CreateSearchConfigRequest(), + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_search_config( + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].search_config_id + mock_val = 'search_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.CreateSearchConfigRequest(), + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateSearchConfigRequest, + dict, +]) +def test_update_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig( + name='name_value', + ) + response = client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +def test_update_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchConfigRequest() + + +def test_update_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateSearchConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchConfigRequest( + ) + +def test_update_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_config] = mock_rpc + request = {} + client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.update_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchConfigRequest() + +@pytest.mark.asyncio +async def test_update_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_search_config] = mock_object + + request = {} + await client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_search_config_async_from_dict(): + await test_update_search_config_async(request_type=dict) + + +def test_update_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateSearchConfigRequest() + + request.search_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + call.return_value = warehouse.SearchConfig() + client.update_search_config(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', + 'search_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateSearchConfigRequest() + + request.search_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + await client.update_search_config(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', + 'search_config.name=name_value', + ) in kw['metadata'] + + +def test_update_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_search_config( + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.UpdateSearchConfigRequest(), + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_search_config( + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.UpdateSearchConfigRequest(), + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetSearchConfigRequest, + dict, +]) +def test_get_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig( + name='name_value', + ) + response = client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +def test_get_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchConfigRequest() + + +def test_get_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetSearchConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchConfigRequest( + name='name_value', + ) + +def test_get_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_config] = mock_rpc + request = {} + client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.get_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchConfigRequest() + +@pytest.mark.asyncio +async def test_get_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_search_config] = mock_object + + request = {} + await client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_search_config_async_from_dict(): + await test_get_search_config_async(request_type=dict) + + +def test_get_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + call.return_value = warehouse.SearchConfig() + client.get_search_config(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_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + await client.get_search_config(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_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.GetSearchConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.GetSearchConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteSearchConfigRequest, + dict, +]) +def test_delete_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchConfigRequest() + + +def test_delete_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteSearchConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchConfigRequest( + name='name_value', + ) + +def test_delete_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_config] = mock_rpc + request = {} + client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchConfigRequest() + +@pytest.mark.asyncio +async def test_delete_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_search_config] = mock_object + + request = {} + await client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_search_config_async_from_dict(): + await test_delete_search_config_async(request_type=dict) + + +def test_delete_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + call.return_value = None + client.delete_search_config(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_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_search_config(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_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__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_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.DeleteSearchConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__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_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.DeleteSearchConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListSearchConfigsRequest, + dict, +]) +def test_list_search_configs(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListSearchConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_search_configs_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 = WarehouseClient( + 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_search_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchConfigsRequest() + + +def test_list_search_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListSearchConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_search_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_configs] = mock_rpc + request = {} + client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchConfigsRequest() + +@pytest.mark.asyncio +async def test_list_search_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_search_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_search_configs] = mock_object + + request = {} + await client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_search_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_configs_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListSearchConfigsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListSearchConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_search_configs_async_from_dict(): + await test_list_search_configs_async(request_type=dict) + + +def test_list_search_configs_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListSearchConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + call.return_value = warehouse.ListSearchConfigsResponse() + client.list_search_configs(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_search_configs_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListSearchConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse()) + await client.list_search_configs(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_search_configs_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_search_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_search_configs_flattened_error(): + client = WarehouseClient( + 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_search_configs( + warehouse.ListSearchConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_search_configs_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_search_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_search_configs_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_configs( + warehouse.ListSearchConfigsRequest(), + parent='parent_value', + ) + + +def test_list_search_configs_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_search_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchConfig) + for i in results) +def test_list_search_configs_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_search_configs(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_search_configs_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_search_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.SearchConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_search_configs_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_search_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateSearchHypernymRequest, + dict, +]) +def test_create_search_hypernym(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + ) + response = client.create_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + + +def test_create_search_hypernym_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 = WarehouseClient( + 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_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchHypernymRequest() + + +def test_create_search_hypernym_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateSearchHypernymRequest( + parent='parent_value', + search_hypernym_id='search_hypernym_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_hypernym(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchHypernymRequest( + parent='parent_value', + search_hypernym_id='search_hypernym_id_value', + ) + +def test_create_search_hypernym_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_hypernym] = mock_rpc + request = {} + client.create_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_hypernym_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + )) + response = await client.create_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchHypernymRequest() + +@pytest.mark.asyncio +async def test_create_search_hypernym_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_search_hypernym in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_search_hypernym] = mock_object + + request = {} + await client.create_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_hypernym_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateSearchHypernymRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + )) + response = await client.create_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + + +@pytest.mark.asyncio +async def test_create_search_hypernym_async_from_dict(): + await test_create_search_hypernym_async(request_type=dict) + + +def test_create_search_hypernym_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateSearchHypernymRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_hypernym), + '__call__') as call: + call.return_value = warehouse.SearchHypernym() + client.create_search_hypernym(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_search_hypernym_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateSearchHypernymRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_hypernym), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym()) + await client.create_search_hypernym(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_search_hypernym_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_search_hypernym( + parent='parent_value', + search_hypernym=warehouse.SearchHypernym(name='name_value'), + search_hypernym_id='search_hypernym_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].search_hypernym + mock_val = warehouse.SearchHypernym(name='name_value') + assert arg == mock_val + arg = args[0].search_hypernym_id + mock_val = 'search_hypernym_id_value' + assert arg == mock_val + + +def test_create_search_hypernym_flattened_error(): + client = WarehouseClient( + 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_search_hypernym( + warehouse.CreateSearchHypernymRequest(), + parent='parent_value', + search_hypernym=warehouse.SearchHypernym(name='name_value'), + search_hypernym_id='search_hypernym_id_value', + ) + +@pytest.mark.asyncio +async def test_create_search_hypernym_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_search_hypernym( + parent='parent_value', + search_hypernym=warehouse.SearchHypernym(name='name_value'), + search_hypernym_id='search_hypernym_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].search_hypernym + mock_val = warehouse.SearchHypernym(name='name_value') + assert arg == mock_val + arg = args[0].search_hypernym_id + mock_val = 'search_hypernym_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_search_hypernym_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_hypernym( + warehouse.CreateSearchHypernymRequest(), + parent='parent_value', + search_hypernym=warehouse.SearchHypernym(name='name_value'), + search_hypernym_id='search_hypernym_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateSearchHypernymRequest, + dict, +]) +def test_update_search_hypernym(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + ) + response = client.update_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + + +def test_update_search_hypernym_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 = WarehouseClient( + 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_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchHypernymRequest() + + +def test_update_search_hypernym_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateSearchHypernymRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_hypernym(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchHypernymRequest( + ) + +def test_update_search_hypernym_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_hypernym] = mock_rpc + request = {} + client.update_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_hypernym_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + )) + response = await client.update_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchHypernymRequest() + +@pytest.mark.asyncio +async def test_update_search_hypernym_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_search_hypernym in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_search_hypernym] = mock_object + + request = {} + await client.update_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_hypernym_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateSearchHypernymRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + )) + response = await client.update_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + + +@pytest.mark.asyncio +async def test_update_search_hypernym_async_from_dict(): + await test_update_search_hypernym_async(request_type=dict) + + +def test_update_search_hypernym_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateSearchHypernymRequest() + + request.search_hypernym.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_hypernym), + '__call__') as call: + call.return_value = warehouse.SearchHypernym() + client.update_search_hypernym(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', + 'search_hypernym.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_search_hypernym_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateSearchHypernymRequest() + + request.search_hypernym.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_hypernym), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym()) + await client.update_search_hypernym(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', + 'search_hypernym.name=name_value', + ) in kw['metadata'] + + +def test_update_search_hypernym_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_search_hypernym( + search_hypernym=warehouse.SearchHypernym(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].search_hypernym + mock_val = warehouse.SearchHypernym(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_search_hypernym_flattened_error(): + client = WarehouseClient( + 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_search_hypernym( + warehouse.UpdateSearchHypernymRequest(), + search_hypernym=warehouse.SearchHypernym(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_search_hypernym_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_search_hypernym( + search_hypernym=warehouse.SearchHypernym(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].search_hypernym + mock_val = warehouse.SearchHypernym(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_search_hypernym_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_hypernym( + warehouse.UpdateSearchHypernymRequest(), + search_hypernym=warehouse.SearchHypernym(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetSearchHypernymRequest, + dict, +]) +def test_get_search_hypernym(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + ) + response = client.get_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + + +def test_get_search_hypernym_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 = WarehouseClient( + 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_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchHypernymRequest() + + +def test_get_search_hypernym_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetSearchHypernymRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_hypernym(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchHypernymRequest( + name='name_value', + ) + +def test_get_search_hypernym_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_hypernym] = mock_rpc + request = {} + client.get_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_hypernym_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + )) + response = await client.get_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchHypernymRequest() + +@pytest.mark.asyncio +async def test_get_search_hypernym_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_search_hypernym in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_search_hypernym] = mock_object + + request = {} + await client.get_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_hypernym_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetSearchHypernymRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + )) + response = await client.get_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + + +@pytest.mark.asyncio +async def test_get_search_hypernym_async_from_dict(): + await test_get_search_hypernym_async(request_type=dict) + + +def test_get_search_hypernym_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetSearchHypernymRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_hypernym), + '__call__') as call: + call.return_value = warehouse.SearchHypernym() + client.get_search_hypernym(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_search_hypernym_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetSearchHypernymRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_hypernym), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym()) + await client.get_search_hypernym(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_search_hypernym_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_search_hypernym( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_search_hypernym_flattened_error(): + client = WarehouseClient( + 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_search_hypernym( + warehouse.GetSearchHypernymRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_search_hypernym_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchHypernym() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchHypernym()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_search_hypernym( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_search_hypernym_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_hypernym( + warehouse.GetSearchHypernymRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteSearchHypernymRequest, + dict, +]) +def test_delete_search_hypernym(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_search_hypernym_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 = WarehouseClient( + 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_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchHypernymRequest() + + +def test_delete_search_hypernym_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteSearchHypernymRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_hypernym), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_hypernym(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchHypernymRequest( + name='name_value', + ) + +def test_delete_search_hypernym_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_hypernym] = mock_rpc + request = {} + client.delete_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_hypernym_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_hypernym() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchHypernymRequest() + +@pytest.mark.asyncio +async def test_delete_search_hypernym_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_search_hypernym in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_search_hypernym] = mock_object + + request = {} + await client.delete_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_hypernym_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteSearchHypernymRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernym), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteSearchHypernymRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_search_hypernym_async_from_dict(): + await test_delete_search_hypernym_async(request_type=dict) + + +def test_delete_search_hypernym_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteSearchHypernymRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_hypernym), + '__call__') as call: + call.return_value = None + client.delete_search_hypernym(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_search_hypernym_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteSearchHypernymRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_hypernym), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_search_hypernym(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_search_hypernym_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_hypernym), + '__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_search_hypernym( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_search_hypernym_flattened_error(): + client = WarehouseClient( + 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_search_hypernym( + warehouse.DeleteSearchHypernymRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_search_hypernym_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_hypernym), + '__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_search_hypernym( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_search_hypernym_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_hypernym( + warehouse.DeleteSearchHypernymRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListSearchHypernymsRequest, + dict, +]) +def test_list_search_hypernyms(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernyms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchHypernymsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_search_hypernyms(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListSearchHypernymsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchHypernymsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_search_hypernyms_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 = WarehouseClient( + 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_search_hypernyms), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_hypernyms() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchHypernymsRequest() + + +def test_list_search_hypernyms_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListSearchHypernymsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_hypernyms(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchHypernymsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_search_hypernyms_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_hypernyms in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_hypernyms] = mock_rpc + request = {} + client.list_search_hypernyms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_hypernyms(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_hypernyms_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchHypernymsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_hypernyms() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchHypernymsRequest() + +@pytest.mark.asyncio +async def test_list_search_hypernyms_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_search_hypernyms in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_search_hypernyms] = mock_object + + request = {} + await client.list_search_hypernyms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_search_hypernyms(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_hypernyms_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListSearchHypernymsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_hypernyms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchHypernymsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_hypernyms(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListSearchHypernymsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchHypernymsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_search_hypernyms_async_from_dict(): + await test_list_search_hypernyms_async(request_type=dict) + + +def test_list_search_hypernyms_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListSearchHypernymsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + call.return_value = warehouse.ListSearchHypernymsResponse() + client.list_search_hypernyms(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_search_hypernyms_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListSearchHypernymsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchHypernymsResponse()) + await client.list_search_hypernyms(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_search_hypernyms_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchHypernymsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_search_hypernyms( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_search_hypernyms_flattened_error(): + client = WarehouseClient( + 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_search_hypernyms( + warehouse.ListSearchHypernymsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_search_hypernyms_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchHypernymsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchHypernymsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_search_hypernyms( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_search_hypernyms_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_hypernyms( + warehouse.ListSearchHypernymsRequest(), + parent='parent_value', + ) + + +def test_list_search_hypernyms_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + next_page_token='abc', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[], + next_page_token='def', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_search_hypernyms(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchHypernym) + for i in results) +def test_list_search_hypernyms_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + next_page_token='abc', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[], + next_page_token='def', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + ), + RuntimeError, + ) + pages = list(client.list_search_hypernyms(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_search_hypernyms_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + next_page_token='abc', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[], + next_page_token='def', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_search_hypernyms(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.SearchHypernym) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_search_hypernyms_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_hypernyms), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + next_page_token='abc', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[], + next_page_token='def', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_search_hypernyms(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.SearchAssetsRequest, + dict, +]) +def test_search_assets(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.SearchAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_assets_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 = WarehouseClient( + 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.search_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchAssetsRequest() + + +def test_search_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.SearchAssetsRequest( + corpus='corpus_value', + page_token='page_token_value', + search_query='search_query_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchAssetsRequest( + corpus='corpus_value', + page_token='page_token_value', + search_query='search_query_value', + ) + +def test_search_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_assets] = mock_rpc + request = {} + client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchAssetsRequest() + +@pytest.mark.asyncio +async def test_search_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.search_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.search_assets] = mock_object + + request = {} + await client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.search_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_search_assets_async(transport: str = 'grpc_asyncio', request_type=warehouse.SearchAssetsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.SearchAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_assets_async_from_dict(): + await test_search_assets_async(request_type=dict) + + +def test_search_assets_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.SearchAssetsRequest() + + request.corpus = 'corpus_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + call.return_value = warehouse.SearchAssetsResponse() + client.search_assets(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', + 'corpus=corpus_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_assets_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.SearchAssetsRequest() + + request.corpus = 'corpus_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchAssetsResponse()) + await client.search_assets(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', + 'corpus=corpus_value', + ) in kw['metadata'] + + +def test_search_assets_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('corpus', ''), + )), + ) + pager = client.search_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in results) +def test_search_assets_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + pages = list(client.search_assets(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_search_assets_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_assets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_assets_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.SearchIndexEndpointRequest, + dict, +]) +def test_search_index_endpoint(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchIndexEndpointResponse( + next_page_token='next_page_token_value', + ) + response = client.search_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.SearchIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchIndexEndpointPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_index_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseClient( + 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.search_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchIndexEndpointRequest() + + +def test_search_index_endpoint_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.SearchIndexEndpointRequest( + text_query='text_query_value', + index_endpoint='index_endpoint_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_index_endpoint(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchIndexEndpointRequest( + text_query='text_query_value', + index_endpoint='index_endpoint_value', + page_token='page_token_value', + ) + +def test_search_index_endpoint_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_index_endpoint] = mock_rpc + request = {} + client.search_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_index_endpoint_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchIndexEndpointResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchIndexEndpointRequest() + +@pytest.mark.asyncio +async def test_search_index_endpoint_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.search_index_endpoint in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.search_index_endpoint] = mock_object + + request = {} + await client.search_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.search_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_search_index_endpoint_async(transport: str = 'grpc_asyncio', request_type=warehouse.SearchIndexEndpointRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchIndexEndpointResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.SearchIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchIndexEndpointAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_index_endpoint_async_from_dict(): + await test_search_index_endpoint_async(request_type=dict) + + +def test_search_index_endpoint_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.SearchIndexEndpointRequest() + + request.index_endpoint = 'index_endpoint_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + call.return_value = warehouse.SearchIndexEndpointResponse() + client.search_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'index_endpoint=index_endpoint_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_index_endpoint_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.SearchIndexEndpointRequest() + + request.index_endpoint = 'index_endpoint_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchIndexEndpointResponse()) + await client.search_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'index_endpoint=index_endpoint_value', + ) in kw['metadata'] + + +def test_search_index_endpoint_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('index_endpoint', ''), + )), + ) + pager = client.search_index_endpoint(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in results) +def test_search_index_endpoint_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + pages = list(client.search_index_endpoint(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_search_index_endpoint_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_index_endpoint(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_index_endpoint_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_index_endpoint), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_index_endpoint(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateIndexEndpointRequest, + dict, +]) +def test_create_index_endpoint(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_index_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseClient( + 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_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateIndexEndpointRequest() + + +def test_create_index_endpoint_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateIndexEndpointRequest( + parent='parent_value', + index_endpoint_id='index_endpoint_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_index_endpoint(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateIndexEndpointRequest( + parent='parent_value', + index_endpoint_id='index_endpoint_id_value', + ) + +def test_create_index_endpoint_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_index_endpoint] = mock_rpc + request = {} + client.create_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_index_endpoint_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateIndexEndpointRequest() + +@pytest.mark.asyncio +async def test_create_index_endpoint_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_index_endpoint in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_index_endpoint] = mock_object + + request = {} + await client.create_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_index_endpoint_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateIndexEndpointRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_index_endpoint_async_from_dict(): + await test_create_index_endpoint_async(request_type=dict) + + +def test_create_index_endpoint_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateIndexEndpointRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index_endpoint), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_index_endpoint_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateIndexEndpointRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_index_endpoint_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_index_endpoint( + parent='parent_value', + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + index_endpoint_id='index_endpoint_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].index_endpoint + mock_val = warehouse.IndexEndpoint(name='name_value') + assert arg == mock_val + arg = args[0].index_endpoint_id + mock_val = 'index_endpoint_id_value' + assert arg == mock_val + + +def test_create_index_endpoint_flattened_error(): + client = WarehouseClient( + 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_index_endpoint( + warehouse.CreateIndexEndpointRequest(), + parent='parent_value', + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + index_endpoint_id='index_endpoint_id_value', + ) + +@pytest.mark.asyncio +async def test_create_index_endpoint_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_index_endpoint( + parent='parent_value', + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + index_endpoint_id='index_endpoint_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].index_endpoint + mock_val = warehouse.IndexEndpoint(name='name_value') + assert arg == mock_val + arg = args[0].index_endpoint_id + mock_val = 'index_endpoint_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_index_endpoint_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index_endpoint( + warehouse.CreateIndexEndpointRequest(), + parent='parent_value', + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + index_endpoint_id='index_endpoint_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetIndexEndpointRequest, + dict, +]) +def test_get_index_endpoint(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.IndexEndpoint( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.IndexEndpoint.State.CREATING, + ) + response = client.get_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.IndexEndpoint) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == warehouse.IndexEndpoint.State.CREATING + + +def test_get_index_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseClient( + 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_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetIndexEndpointRequest() + + +def test_get_index_endpoint_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetIndexEndpointRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_index_endpoint(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetIndexEndpointRequest( + name='name_value', + ) + +def test_get_index_endpoint_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_index_endpoint] = mock_rpc + request = {} + client.get_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_index_endpoint_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.IndexEndpoint( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.IndexEndpoint.State.CREATING, + )) + response = await client.get_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetIndexEndpointRequest() + +@pytest.mark.asyncio +async def test_get_index_endpoint_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_index_endpoint in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_index_endpoint] = mock_object + + request = {} + await client.get_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_index_endpoint_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetIndexEndpointRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.IndexEndpoint( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.IndexEndpoint.State.CREATING, + )) + response = await client.get_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.IndexEndpoint) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == warehouse.IndexEndpoint.State.CREATING + + +@pytest.mark.asyncio +async def test_get_index_endpoint_async_from_dict(): + await test_get_index_endpoint_async(request_type=dict) + + +def test_get_index_endpoint_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetIndexEndpointRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index_endpoint), + '__call__') as call: + call.return_value = warehouse.IndexEndpoint() + client.get_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_index_endpoint_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetIndexEndpointRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.IndexEndpoint()) + await client.get_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_index_endpoint_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.IndexEndpoint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_index_endpoint( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_index_endpoint_flattened_error(): + client = WarehouseClient( + 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_index_endpoint( + warehouse.GetIndexEndpointRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_index_endpoint_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.IndexEndpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.IndexEndpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_index_endpoint( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_index_endpoint_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index_endpoint( + warehouse.GetIndexEndpointRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListIndexEndpointsRequest, + dict, +]) +def test_list_index_endpoints(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListIndexEndpointsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_index_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListIndexEndpointsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIndexEndpointsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_index_endpoints_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseClient( + 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_index_endpoints), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_index_endpoints() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListIndexEndpointsRequest() + + +def test_list_index_endpoints_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListIndexEndpointsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_index_endpoints(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListIndexEndpointsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_index_endpoints_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_index_endpoints in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_index_endpoints] = mock_rpc + request = {} + client.list_index_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_index_endpoints(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_index_endpoints_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexEndpointsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_index_endpoints() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListIndexEndpointsRequest() + +@pytest.mark.asyncio +async def test_list_index_endpoints_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_index_endpoints in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_index_endpoints] = mock_object + + request = {} + await client.list_index_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_index_endpoints(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_index_endpoints_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListIndexEndpointsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexEndpointsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_index_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListIndexEndpointsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIndexEndpointsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_index_endpoints_async_from_dict(): + await test_list_index_endpoints_async(request_type=dict) + + +def test_list_index_endpoints_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListIndexEndpointsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + call.return_value = warehouse.ListIndexEndpointsResponse() + client.list_index_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_index_endpoints_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListIndexEndpointsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexEndpointsResponse()) + await client.list_index_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_index_endpoints_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListIndexEndpointsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_index_endpoints( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_index_endpoints_flattened_error(): + client = WarehouseClient( + 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_index_endpoints( + warehouse.ListIndexEndpointsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_index_endpoints_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListIndexEndpointsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListIndexEndpointsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_index_endpoints( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_index_endpoints_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index_endpoints( + warehouse.ListIndexEndpointsRequest(), + parent='parent_value', + ) + + +def test_list_index_endpoints_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + next_page_token='abc', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[], + next_page_token='def', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_index_endpoints(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.IndexEndpoint) + for i in results) +def test_list_index_endpoints_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + next_page_token='abc', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[], + next_page_token='def', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + ), + RuntimeError, + ) + pages = list(client.list_index_endpoints(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_index_endpoints_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + next_page_token='abc', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[], + next_page_token='def', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_index_endpoints(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.IndexEndpoint) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_index_endpoints_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_index_endpoints), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + next_page_token='abc', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[], + next_page_token='def', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_index_endpoints(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateIndexEndpointRequest, + dict, +]) +def test_update_index_endpoint(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_index_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseClient( + 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_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateIndexEndpointRequest() + + +def test_update_index_endpoint_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateIndexEndpointRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_index_endpoint(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateIndexEndpointRequest( + ) + +def test_update_index_endpoint_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_index_endpoint] = mock_rpc + request = {} + client.update_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_index_endpoint_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateIndexEndpointRequest() + +@pytest.mark.asyncio +async def test_update_index_endpoint_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_index_endpoint in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_index_endpoint] = mock_object + + request = {} + await client.update_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_index_endpoint_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateIndexEndpointRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_index_endpoint_async_from_dict(): + await test_update_index_endpoint_async(request_type=dict) + + +def test_update_index_endpoint_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateIndexEndpointRequest() + + request.index_endpoint.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index_endpoint), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'index_endpoint.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_index_endpoint_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateIndexEndpointRequest() + + request.index_endpoint.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'index_endpoint.name=name_value', + ) in kw['metadata'] + + +def test_update_index_endpoint_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_index_endpoint( + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].index_endpoint + mock_val = warehouse.IndexEndpoint(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_index_endpoint_flattened_error(): + client = WarehouseClient( + 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_index_endpoint( + warehouse.UpdateIndexEndpointRequest(), + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_index_endpoint_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_index_endpoint( + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].index_endpoint + mock_val = warehouse.IndexEndpoint(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_index_endpoint_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index_endpoint( + warehouse.UpdateIndexEndpointRequest(), + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteIndexEndpointRequest, + dict, +]) +def test_delete_index_endpoint(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_index_endpoint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseClient( + 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_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteIndexEndpointRequest() + + +def test_delete_index_endpoint_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteIndexEndpointRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index_endpoint), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_index_endpoint(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteIndexEndpointRequest( + name='name_value', + ) + +def test_delete_index_endpoint_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_index_endpoint] = mock_rpc + request = {} + client.delete_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_index_endpoint_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_index_endpoint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteIndexEndpointRequest() + +@pytest.mark.asyncio +async def test_delete_index_endpoint_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_index_endpoint in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_index_endpoint] = mock_object + + request = {} + await client.delete_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_index_endpoint_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteIndexEndpointRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteIndexEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_index_endpoint_async_from_dict(): + await test_delete_index_endpoint_async(request_type=dict) + + +def test_delete_index_endpoint_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteIndexEndpointRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index_endpoint), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_index_endpoint_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteIndexEndpointRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index_endpoint), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_index_endpoint_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_index_endpoint( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_index_endpoint_flattened_error(): + client = WarehouseClient( + 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_index_endpoint( + warehouse.DeleteIndexEndpointRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_index_endpoint_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_index_endpoint), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_index_endpoint( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_index_endpoint_flattened_error_async(): + client = WarehouseAsyncClient( + 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_index_endpoint( + warehouse.DeleteIndexEndpointRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeployIndexRequest, + dict, +]) +def test_deploy_index(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.deploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeployIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_deploy_index_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 = WarehouseClient( + 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.deploy_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.deploy_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeployIndexRequest() + + +def test_deploy_index_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeployIndexRequest( + index_endpoint='index_endpoint_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.deploy_index(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeployIndexRequest( + index_endpoint='index_endpoint_value', + ) + +def test_deploy_index_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.deploy_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.deploy_index] = mock_rpc + request = {} + client.deploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.deploy_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_deploy_index_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.deploy_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeployIndexRequest() + +@pytest.mark.asyncio +async def test_deploy_index_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.deploy_index in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.deploy_index] = mock_object + + request = {} + await client.deploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.deploy_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_deploy_index_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeployIndexRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.deploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeployIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_deploy_index_async_from_dict(): + await test_deploy_index_async(request_type=dict) + + +def test_deploy_index_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeployIndexRequest() + + request.index_endpoint = 'index_endpoint_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_index), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.deploy_index(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', + 'index_endpoint=index_endpoint_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_deploy_index_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeployIndexRequest() + + request.index_endpoint = 'index_endpoint_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_index), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.deploy_index(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', + 'index_endpoint=index_endpoint_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.UndeployIndexRequest, + dict, +]) +def test_undeploy_index(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.undeploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UndeployIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_undeploy_index_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 = WarehouseClient( + 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.undeploy_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.undeploy_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UndeployIndexRequest() + + +def test_undeploy_index_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UndeployIndexRequest( + index_endpoint='index_endpoint_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_index), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.undeploy_index(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UndeployIndexRequest( + index_endpoint='index_endpoint_value', + ) + +def test_undeploy_index_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.undeploy_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undeploy_index] = mock_rpc + request = {} + client.undeploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.undeploy_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_undeploy_index_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.undeploy_index() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UndeployIndexRequest() + +@pytest.mark.asyncio +async def test_undeploy_index_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.undeploy_index in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.undeploy_index] = mock_object + + request = {} + await client.undeploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.undeploy_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_undeploy_index_async(transport: str = 'grpc_asyncio', request_type=warehouse.UndeployIndexRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_index), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.undeploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UndeployIndexRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_undeploy_index_async_from_dict(): + await test_undeploy_index_async(request_type=dict) + + +def test_undeploy_index_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UndeployIndexRequest() + + request.index_endpoint = 'index_endpoint_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_index), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.undeploy_index(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', + 'index_endpoint=index_endpoint_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_undeploy_index_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UndeployIndexRequest() + + request.index_endpoint = 'index_endpoint_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_index), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.undeploy_index(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', + 'index_endpoint=index_endpoint_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateCollectionRequest, + dict, +]) +def test_create_collection(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_collection_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 = WarehouseClient( + 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_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCollectionRequest() + + +def test_create_collection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateCollectionRequest( + parent='parent_value', + collection_id='collection_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_collection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCollectionRequest( + parent='parent_value', + collection_id='collection_id_value', + ) + +def test_create_collection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_collection] = mock_rpc + request = {} + client.create_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_collection_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCollectionRequest() + +@pytest.mark.asyncio +async def test_create_collection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_collection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_collection] = mock_object + + request = {} + await client.create_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_collection_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateCollectionRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_collection_async_from_dict(): + await test_create_collection_async(request_type=dict) + + +def test_create_collection_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateCollectionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_collection), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_collection(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_collection_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateCollectionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_collection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_collection(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_collection_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_collection( + parent='parent_value', + collection=warehouse.Collection(name='name_value'), + collection_id='collection_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].collection + mock_val = warehouse.Collection(name='name_value') + assert arg == mock_val + arg = args[0].collection_id + mock_val = 'collection_id_value' + assert arg == mock_val + + +def test_create_collection_flattened_error(): + client = WarehouseClient( + 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_collection( + warehouse.CreateCollectionRequest(), + parent='parent_value', + collection=warehouse.Collection(name='name_value'), + collection_id='collection_id_value', + ) + +@pytest.mark.asyncio +async def test_create_collection_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_collection( + parent='parent_value', + collection=warehouse.Collection(name='name_value'), + collection_id='collection_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].collection + mock_val = warehouse.Collection(name='name_value') + assert arg == mock_val + arg = args[0].collection_id + mock_val = 'collection_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_collection_flattened_error_async(): + client = WarehouseAsyncClient( + 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_collection( + warehouse.CreateCollectionRequest(), + parent='parent_value', + collection=warehouse.Collection(name='name_value'), + collection_id='collection_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteCollectionRequest, + dict, +]) +def test_delete_collection(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_collection_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 = WarehouseClient( + 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_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCollectionRequest() + + +def test_delete_collection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteCollectionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_collection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCollectionRequest( + name='name_value', + ) + +def test_delete_collection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_collection] = mock_rpc + request = {} + client.delete_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_collection_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCollectionRequest() + +@pytest.mark.asyncio +async def test_delete_collection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_collection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_collection] = mock_object + + request = {} + await client.delete_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_collection_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteCollectionRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_collection_async_from_dict(): + await test_delete_collection_async(request_type=dict) + + +def test_delete_collection_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteCollectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_collection), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_collection(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_collection_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteCollectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_collection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_collection(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_collection_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_collection( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_collection_flattened_error(): + client = WarehouseClient( + 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_collection( + warehouse.DeleteCollectionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_collection_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_collection( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_collection_flattened_error_async(): + client = WarehouseAsyncClient( + 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_collection( + warehouse.DeleteCollectionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetCollectionRequest, + dict, +]) +def test_get_collection(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Collection) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_collection_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 = WarehouseClient( + 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_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCollectionRequest() + + +def test_get_collection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetCollectionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_collection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCollectionRequest( + name='name_value', + ) + +def test_get_collection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_collection] = mock_rpc + request = {} + client.get_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_collection_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCollectionRequest() + +@pytest.mark.asyncio +async def test_get_collection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_collection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_collection] = mock_object + + request = {} + await client.get_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_collection_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetCollectionRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Collection) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_collection_async_from_dict(): + await test_get_collection_async(request_type=dict) + + +def test_get_collection_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetCollectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_collection), + '__call__') as call: + call.return_value = warehouse.Collection() + client.get_collection(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_collection_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetCollectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_collection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection()) + await client.get_collection(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_collection_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Collection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_collection( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_collection_flattened_error(): + client = WarehouseClient( + 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_collection( + warehouse.GetCollectionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_collection_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Collection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_collection( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_collection_flattened_error_async(): + client = WarehouseAsyncClient( + 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_collection( + warehouse.GetCollectionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateCollectionRequest, + dict, +]) +def test_update_collection(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Collection) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_collection_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 = WarehouseClient( + 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_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCollectionRequest() + + +def test_update_collection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateCollectionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_collection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCollectionRequest( + ) + +def test_update_collection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_collection] = mock_rpc + request = {} + client.update_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_collection_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCollectionRequest() + +@pytest.mark.asyncio +async def test_update_collection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_collection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_collection] = mock_object + + request = {} + await client.update_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_collection_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateCollectionRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Collection) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_collection_async_from_dict(): + await test_update_collection_async(request_type=dict) + + +def test_update_collection_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateCollectionRequest() + + request.collection.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_collection), + '__call__') as call: + call.return_value = warehouse.Collection() + client.update_collection(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', + 'collection.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_collection_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateCollectionRequest() + + request.collection.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_collection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection()) + await client.update_collection(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', + 'collection.name=name_value', + ) in kw['metadata'] + + +def test_update_collection_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Collection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_collection( + collection=warehouse.Collection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].collection + mock_val = warehouse.Collection(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_collection_flattened_error(): + client = WarehouseClient( + 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_collection( + warehouse.UpdateCollectionRequest(), + collection=warehouse.Collection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_collection_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Collection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Collection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_collection( + collection=warehouse.Collection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].collection + mock_val = warehouse.Collection(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_collection_flattened_error_async(): + client = WarehouseAsyncClient( + 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_collection( + warehouse.UpdateCollectionRequest(), + collection=warehouse.Collection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListCollectionsRequest, + dict, +]) +def test_list_collections(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCollectionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_collections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListCollectionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCollectionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_collections_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 = WarehouseClient( + 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_collections), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_collections() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCollectionsRequest() + + +def test_list_collections_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListCollectionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_collections(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCollectionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_collections_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_collections in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_collections] = mock_rpc + request = {} + client.list_collections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_collections(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_collections_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCollectionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_collections() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCollectionsRequest() + +@pytest.mark.asyncio +async def test_list_collections_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_collections in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_collections] = mock_object + + request = {} + await client.list_collections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_collections(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_collections_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListCollectionsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_collections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCollectionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_collections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListCollectionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCollectionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_collections_async_from_dict(): + await test_list_collections_async(request_type=dict) + + +def test_list_collections_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListCollectionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + call.return_value = warehouse.ListCollectionsResponse() + client.list_collections(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_collections_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListCollectionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCollectionsResponse()) + await client.list_collections(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_collections_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCollectionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_collections( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_collections_flattened_error(): + client = WarehouseClient( + 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_collections( + warehouse.ListCollectionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_collections_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCollectionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCollectionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_collections( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_collections_flattened_error_async(): + client = WarehouseAsyncClient( + 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_collections( + warehouse.ListCollectionsRequest(), + parent='parent_value', + ) + + +def test_list_collections_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + warehouse.Collection(), + ], + next_page_token='abc', + ), + warehouse.ListCollectionsResponse( + collections=[], + next_page_token='def', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + ], + next_page_token='ghi', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_collections(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Collection) + for i in results) +def test_list_collections_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + warehouse.Collection(), + ], + next_page_token='abc', + ), + warehouse.ListCollectionsResponse( + collections=[], + next_page_token='def', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + ], + next_page_token='ghi', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + ], + ), + RuntimeError, + ) + pages = list(client.list_collections(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_collections_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + warehouse.Collection(), + ], + next_page_token='abc', + ), + warehouse.ListCollectionsResponse( + collections=[], + next_page_token='def', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + ], + next_page_token='ghi', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_collections(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Collection) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_collections_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_collections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + warehouse.Collection(), + ], + next_page_token='abc', + ), + warehouse.ListCollectionsResponse( + collections=[], + next_page_token='def', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + ], + next_page_token='ghi', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_collections(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.AddCollectionItemRequest, + dict, +]) +def test_add_collection_item(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.AddCollectionItemResponse( + ) + response = client.add_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.AddCollectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.AddCollectionItemResponse) + + +def test_add_collection_item_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 = WarehouseClient( + 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.add_collection_item), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_collection_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AddCollectionItemRequest() + + +def test_add_collection_item_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.AddCollectionItemRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_collection_item(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AddCollectionItemRequest( + ) + +def test_add_collection_item_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_collection_item in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_collection_item] = mock_rpc + request = {} + client.add_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.add_collection_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_add_collection_item_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.AddCollectionItemResponse( + )) + response = await client.add_collection_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.AddCollectionItemRequest() + +@pytest.mark.asyncio +async def test_add_collection_item_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.add_collection_item in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.add_collection_item] = mock_object + + request = {} + await client.add_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.add_collection_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_add_collection_item_async(transport: str = 'grpc_asyncio', request_type=warehouse.AddCollectionItemRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.AddCollectionItemResponse( + )) + response = await client.add_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.AddCollectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.AddCollectionItemResponse) + + +@pytest.mark.asyncio +async def test_add_collection_item_async_from_dict(): + await test_add_collection_item_async(request_type=dict) + + +def test_add_collection_item_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.AddCollectionItemRequest() + + request.item.collection = 'collection_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + call.return_value = warehouse.AddCollectionItemResponse() + client.add_collection_item(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', + 'item.collection=collection_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_collection_item_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.AddCollectionItemRequest() + + request.item.collection = 'collection_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.AddCollectionItemResponse()) + await client.add_collection_item(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', + 'item.collection=collection_value', + ) in kw['metadata'] + + +def test_add_collection_item_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.AddCollectionItemResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_collection_item( + item=warehouse.CollectionItem(collection='collection_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].item + mock_val = warehouse.CollectionItem(collection='collection_value') + assert arg == mock_val + + +def test_add_collection_item_flattened_error(): + client = WarehouseClient( + 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.add_collection_item( + warehouse.AddCollectionItemRequest(), + item=warehouse.CollectionItem(collection='collection_value'), + ) + +@pytest.mark.asyncio +async def test_add_collection_item_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.AddCollectionItemResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.AddCollectionItemResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_collection_item( + item=warehouse.CollectionItem(collection='collection_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].item + mock_val = warehouse.CollectionItem(collection='collection_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_collection_item_flattened_error_async(): + client = WarehouseAsyncClient( + 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.add_collection_item( + warehouse.AddCollectionItemRequest(), + item=warehouse.CollectionItem(collection='collection_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.RemoveCollectionItemRequest, + dict, +]) +def test_remove_collection_item(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.RemoveCollectionItemResponse( + ) + response = client.remove_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.RemoveCollectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.RemoveCollectionItemResponse) + + +def test_remove_collection_item_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 = WarehouseClient( + 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.remove_collection_item), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_collection_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.RemoveCollectionItemRequest() + + +def test_remove_collection_item_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.RemoveCollectionItemRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_collection_item(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.RemoveCollectionItemRequest( + ) + +def test_remove_collection_item_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_collection_item in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_collection_item] = mock_rpc + request = {} + client.remove_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.remove_collection_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_collection_item_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.RemoveCollectionItemResponse( + )) + response = await client.remove_collection_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.RemoveCollectionItemRequest() + +@pytest.mark.asyncio +async def test_remove_collection_item_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.remove_collection_item in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.remove_collection_item] = mock_object + + request = {} + await client.remove_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.remove_collection_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_collection_item_async(transport: str = 'grpc_asyncio', request_type=warehouse.RemoveCollectionItemRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.RemoveCollectionItemResponse( + )) + response = await client.remove_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.RemoveCollectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.RemoveCollectionItemResponse) + + +@pytest.mark.asyncio +async def test_remove_collection_item_async_from_dict(): + await test_remove_collection_item_async(request_type=dict) + + +def test_remove_collection_item_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.RemoveCollectionItemRequest() + + request.item.collection = 'collection_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + call.return_value = warehouse.RemoveCollectionItemResponse() + client.remove_collection_item(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', + 'item.collection=collection_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_collection_item_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.RemoveCollectionItemRequest() + + request.item.collection = 'collection_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.RemoveCollectionItemResponse()) + await client.remove_collection_item(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', + 'item.collection=collection_value', + ) in kw['metadata'] + + +def test_remove_collection_item_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.RemoveCollectionItemResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_collection_item( + item=warehouse.CollectionItem(collection='collection_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].item + mock_val = warehouse.CollectionItem(collection='collection_value') + assert arg == mock_val + + +def test_remove_collection_item_flattened_error(): + client = WarehouseClient( + 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.remove_collection_item( + warehouse.RemoveCollectionItemRequest(), + item=warehouse.CollectionItem(collection='collection_value'), + ) + +@pytest.mark.asyncio +async def test_remove_collection_item_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_collection_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.RemoveCollectionItemResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.RemoveCollectionItemResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_collection_item( + item=warehouse.CollectionItem(collection='collection_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].item + mock_val = warehouse.CollectionItem(collection='collection_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_collection_item_flattened_error_async(): + client = WarehouseAsyncClient( + 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.remove_collection_item( + warehouse.RemoveCollectionItemRequest(), + item=warehouse.CollectionItem(collection='collection_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ViewCollectionItemsRequest, + dict, +]) +def test_view_collection_items(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ViewCollectionItemsResponse( + next_page_token='next_page_token_value', + ) + response = client.view_collection_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ViewCollectionItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ViewCollectionItemsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_view_collection_items_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 = WarehouseClient( + 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.view_collection_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.view_collection_items() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ViewCollectionItemsRequest() + + +def test_view_collection_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ViewCollectionItemsRequest( + collection='collection_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.view_collection_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ViewCollectionItemsRequest( + collection='collection_value', + page_token='page_token_value', + ) + +def test_view_collection_items_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.view_collection_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.view_collection_items] = mock_rpc + request = {} + client.view_collection_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.view_collection_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_view_collection_items_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewCollectionItemsResponse( + next_page_token='next_page_token_value', + )) + response = await client.view_collection_items() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ViewCollectionItemsRequest() + +@pytest.mark.asyncio +async def test_view_collection_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.view_collection_items in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.view_collection_items] = mock_object + + request = {} + await client.view_collection_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.view_collection_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_view_collection_items_async(transport: str = 'grpc_asyncio', request_type=warehouse.ViewCollectionItemsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewCollectionItemsResponse( + next_page_token='next_page_token_value', + )) + response = await client.view_collection_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ViewCollectionItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ViewCollectionItemsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_view_collection_items_async_from_dict(): + await test_view_collection_items_async(request_type=dict) + + +def test_view_collection_items_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ViewCollectionItemsRequest() + + request.collection = 'collection_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + call.return_value = warehouse.ViewCollectionItemsResponse() + client.view_collection_items(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', + 'collection=collection_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_view_collection_items_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ViewCollectionItemsRequest() + + request.collection = 'collection_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewCollectionItemsResponse()) + await client.view_collection_items(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', + 'collection=collection_value', + ) in kw['metadata'] + + +def test_view_collection_items_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ViewCollectionItemsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.view_collection_items( + collection='collection_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].collection + mock_val = 'collection_value' + assert arg == mock_val + + +def test_view_collection_items_flattened_error(): + client = WarehouseClient( + 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.view_collection_items( + warehouse.ViewCollectionItemsRequest(), + collection='collection_value', + ) + +@pytest.mark.asyncio +async def test_view_collection_items_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ViewCollectionItemsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ViewCollectionItemsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.view_collection_items( + collection='collection_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].collection + mock_val = 'collection_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_view_collection_items_flattened_error_async(): + client = WarehouseAsyncClient( + 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.view_collection_items( + warehouse.ViewCollectionItemsRequest(), + collection='collection_value', + ) + + +def test_view_collection_items_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + next_page_token='abc', + ), + warehouse.ViewCollectionItemsResponse( + items=[], + next_page_token='def', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + ], + next_page_token='ghi', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('collection', ''), + )), + ) + pager = client.view_collection_items(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.CollectionItem) + for i in results) +def test_view_collection_items_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + next_page_token='abc', + ), + warehouse.ViewCollectionItemsResponse( + items=[], + next_page_token='def', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + ], + next_page_token='ghi', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + ), + RuntimeError, + ) + pages = list(client.view_collection_items(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_view_collection_items_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + next_page_token='abc', + ), + warehouse.ViewCollectionItemsResponse( + items=[], + next_page_token='def', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + ], + next_page_token='ghi', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.view_collection_items(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.CollectionItem) + for i in responses) + + +@pytest.mark.asyncio +async def test_view_collection_items_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.view_collection_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + next_page_token='abc', + ), + warehouse.ViewCollectionItemsResponse( + items=[], + next_page_token='def', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + ], + next_page_token='ghi', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.view_collection_items(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAssetRequest, + dict, +]) +def test_create_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["asset"] = {'name': 'name_value', 'ttl': {'seconds': 751, 'nanos': 543}, 'asset_gcs_source': {'gcs_uri': 'gcs_uri_value'}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateAssetRequest.meta.fields["asset"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["asset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["asset"][field])): + del request_init["asset"][field][i][subfield] + else: + del request_init["asset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + +def test_create_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_asset] = mock_rpc + + request = {} + client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_asset_rest_required_fields(request_type=warehouse.CreateAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_asset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetId", )) & set(("parent", "asset", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateAssetRequest.pb(warehouse.CreateAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Asset.to_json(warehouse.Asset()) + + request = warehouse.CreateAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Asset() + + client.create_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_asset(request) + + +def test_create_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/assets" % client.transport._host, args[1]) + + +def test_create_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_asset( + warehouse.CreateAssetRequest(), + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + +def test_create_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAssetRequest, + dict, +]) +def test_update_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'asset': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'}} + request_init["asset"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4', 'ttl': {'seconds': 751, 'nanos': 543}, 'asset_gcs_source': {'gcs_uri': 'gcs_uri_value'}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateAssetRequest.meta.fields["asset"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["asset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["asset"][field])): + del request_init["asset"][field][i][subfield] + else: + del request_init["asset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + +def test_update_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_asset] = mock_rpc + + request = {} + client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_asset_rest_required_fields(request_type=warehouse.UpdateAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_asset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("asset", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateAssetRequest.pb(warehouse.UpdateAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Asset.to_json(warehouse.Asset()) + + request = warehouse.UpdateAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Asset() + + client.update_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'asset': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_asset(request) + + +def test_update_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + + # get arguments that satisfy an http rule for this method + sample_request = {'asset': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{asset.name=projects/*/locations/*/corpora/*/assets/*}" % client.transport._host, args[1]) + + +def test_update_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_asset( + warehouse.UpdateAssetRequest(), + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAssetRequest, + dict, +]) +def test_get_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + +def test_get_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_asset] = mock_rpc + + request = {} + client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_asset_rest_required_fields(request_type=warehouse.GetAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetAssetRequest.pb(warehouse.GetAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Asset.to_json(warehouse.Asset()) + + request = warehouse.GetAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Asset() + + client.get_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_asset(request) + + +def test_get_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/assets/*}" % client.transport._host, args[1]) + + +def test_get_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_asset( + warehouse.GetAssetRequest(), + name='name_value', + ) + + +def test_get_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_assets_rest_required_fields(request_type=warehouse.ListAssetsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListAssetsRequest.pb(warehouse.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListAssetsResponse.to_json(warehouse.ListAssetsResponse()) + + request = warehouse.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListAssetsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_assets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/assets" % client.transport._host, args[1]) + + +def test_list_assets_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_assets( + warehouse.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListAssetsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Asset) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAssetRequest, + dict, +]) +def test_delete_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_asset(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_asset] = mock_rpc + + request = {} + client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_asset_rest_required_fields(request_type=warehouse.DeleteAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_delete_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.DeleteAssetRequest.pb(warehouse.DeleteAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.DeleteAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_asset(request) + + +def test_delete_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/assets/*}" % client.transport._host, args[1]) + + +def test_delete_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_asset( + warehouse.DeleteAssetRequest(), + name='name_value', + ) + + +def test_delete_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UploadAssetRequest, + dict, +]) +def test_upload_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.upload_asset(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_upload_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.upload_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.upload_asset] = mock_rpc + + request = {} + client.upload_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.upload_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_upload_asset_rest_required_fields(request_type=warehouse.UploadAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).upload_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).upload_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.upload_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_upload_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.upload_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_upload_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_upload_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_upload_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UploadAssetRequest.pb(warehouse.UploadAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.UploadAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.upload_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_upload_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.UploadAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.upload_asset(request) + + +def test_upload_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GenerateRetrievalUrlRequest, + dict, +]) +def test_generate_retrieval_url_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.GenerateRetrievalUrlResponse( + signed_uri='signed_uri_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.GenerateRetrievalUrlResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_retrieval_url(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateRetrievalUrlResponse) + assert response.signed_uri == 'signed_uri_value' + +def test_generate_retrieval_url_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_retrieval_url in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_retrieval_url] = mock_rpc + + request = {} + client.generate_retrieval_url(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_retrieval_url(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_retrieval_url_rest_required_fields(request_type=warehouse.GenerateRetrievalUrlRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_retrieval_url._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_retrieval_url._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.GenerateRetrievalUrlResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.GenerateRetrievalUrlResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.generate_retrieval_url(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_retrieval_url_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_retrieval_url._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_retrieval_url_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_generate_retrieval_url") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_generate_retrieval_url") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GenerateRetrievalUrlRequest.pb(warehouse.GenerateRetrievalUrlRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.GenerateRetrievalUrlResponse.to_json(warehouse.GenerateRetrievalUrlResponse()) + + request = warehouse.GenerateRetrievalUrlRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.GenerateRetrievalUrlResponse() + + client.generate_retrieval_url(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_retrieval_url_rest_bad_request(transport: str = 'rest', request_type=warehouse.GenerateRetrievalUrlRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_retrieval_url(request) + + +def test_generate_retrieval_url_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.AnalyzeAssetRequest, + dict, +]) +def test_analyze_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.analyze_asset(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_analyze_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.analyze_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.analyze_asset] = mock_rpc + + request = {} + client.analyze_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.analyze_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_analyze_asset_rest_required_fields(request_type=warehouse.AnalyzeAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.analyze_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_analyze_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_analyze_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.AnalyzeAssetRequest.pb(warehouse.AnalyzeAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.AnalyzeAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.analyze_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.AnalyzeAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_asset(request) + + +def test_analyze_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.IndexAssetRequest, + dict, +]) +def test_index_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.index_asset(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_index_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.index_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.index_asset] = mock_rpc + + request = {} + client.index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.index_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_index_asset_rest_required_fields(request_type=warehouse.IndexAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).index_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).index_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.index_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_index_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.index_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_index_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_index_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_index_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.IndexAssetRequest.pb(warehouse.IndexAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.IndexAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.index_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_index_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.IndexAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.index_asset(request) + + +def test_index_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.RemoveIndexAssetRequest, + dict, +]) +def test_remove_index_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.remove_index_asset(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_remove_index_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_index_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_index_asset] = mock_rpc + + request = {} + client.remove_index_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_index_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_index_asset_rest_required_fields(request_type=warehouse.RemoveIndexAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_index_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_index_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.remove_index_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_index_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_index_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_index_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_remove_index_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_remove_index_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.RemoveIndexAssetRequest.pb(warehouse.RemoveIndexAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.RemoveIndexAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.remove_index_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_index_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.RemoveIndexAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.remove_index_asset(request) + + +def test_remove_index_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ViewIndexedAssetsRequest, + dict, +]) +def test_view_indexed_assets_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'index': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ViewIndexedAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ViewIndexedAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.view_indexed_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ViewIndexedAssetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_view_indexed_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.view_indexed_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.view_indexed_assets] = mock_rpc + + request = {} + client.view_indexed_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.view_indexed_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_view_indexed_assets_rest_required_fields(request_type=warehouse.ViewIndexedAssetsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["index"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).view_indexed_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["index"] = 'index_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).view_indexed_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "index" in jsonified_request + assert jsonified_request["index"] == 'index_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ViewIndexedAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ViewIndexedAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.view_indexed_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_view_indexed_assets_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.view_indexed_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("index", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_view_indexed_assets_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_view_indexed_assets") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_view_indexed_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ViewIndexedAssetsRequest.pb(warehouse.ViewIndexedAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ViewIndexedAssetsResponse.to_json(warehouse.ViewIndexedAssetsResponse()) + + request = warehouse.ViewIndexedAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ViewIndexedAssetsResponse() + + client.view_indexed_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_view_indexed_assets_rest_bad_request(transport: str = 'rest', request_type=warehouse.ViewIndexedAssetsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'index': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.view_indexed_assets(request) + + +def test_view_indexed_assets_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ViewIndexedAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'index': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + index='index_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ViewIndexedAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.view_indexed_assets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{index=projects/*/locations/*/corpora/*/indexes/*}:viewAssets" % client.transport._host, args[1]) + + +def test_view_indexed_assets_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.view_indexed_assets( + warehouse.ViewIndexedAssetsRequest(), + index='index_value', + ) + + +def test_view_indexed_assets_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + next_page_token='abc', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[], + next_page_token='def', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + ], + next_page_token='ghi', + ), + warehouse.ViewIndexedAssetsResponse( + indexed_assets=[ + warehouse.IndexedAsset(), + warehouse.IndexedAsset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ViewIndexedAssetsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'index': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + + pager = client.view_indexed_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.IndexedAsset) + for i in results) + + pages = list(client.view_indexed_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateIndexRequest, + dict, +]) +def test_create_index_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["index"] = {'entire_corpus': True, 'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'deployed_indexes': [{'index_endpoint': 'index_endpoint_value'}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateIndexRequest.meta.fields["index"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["index"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["index"][field])): + del request_init["index"][field][i][subfield] + else: + del request_init["index"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_index(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_index_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_index] = mock_rpc + + request = {} + client.create_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_index_rest_required_fields(request_type=warehouse.CreateIndexRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_index._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("index_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_index(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_index_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_index._get_unset_required_fields({}) + assert set(unset_fields) == (set(("indexId", )) & set(("parent", "index", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_index_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_index") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_index") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateIndexRequest.pb(warehouse.CreateIndexRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.CreateIndexRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_index(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_index_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateIndexRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_index(request) + + +def test_create_index_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + index=warehouse.Index(entire_corpus=True), + index_id='index_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_index(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/indexes" % client.transport._host, args[1]) + + +def test_create_index_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_index( + warehouse.CreateIndexRequest(), + parent='parent_value', + index=warehouse.Index(entire_corpus=True), + index_id='index_id_value', + ) + + +def test_create_index_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateIndexRequest, + dict, +]) +def test_update_index_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'index': {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'}} + request_init["index"] = {'entire_corpus': True, 'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'deployed_indexes': [{'index_endpoint': 'index_endpoint_value'}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateIndexRequest.meta.fields["index"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["index"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["index"][field])): + del request_init["index"][field][i][subfield] + else: + del request_init["index"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_index(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_index_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_index] = mock_rpc + + request = {} + client.update_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_index_rest_required_fields(request_type=warehouse.UpdateIndexRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_index._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_index(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_index_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_index._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("index", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_index_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_index") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_index") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateIndexRequest.pb(warehouse.UpdateIndexRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.UpdateIndexRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_index(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_index_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateIndexRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'index': {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_index(request) + + +def test_update_index_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'index': {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + index=warehouse.Index(entire_corpus=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_index(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{index.name=projects/*/locations/*/corpora/*/indexes/*}" % client.transport._host, args[1]) + + +def test_update_index_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_index( + warehouse.UpdateIndexRequest(), + index=warehouse.Index(entire_corpus=True), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_index_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetIndexRequest, + dict, +]) +def test_get_index_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Index( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.Index.State.CREATING, + entire_corpus=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Index.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_index(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Index) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == warehouse.Index.State.CREATING + +def test_get_index_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_index] = mock_rpc + + request = {} + client.get_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_index_rest_required_fields(request_type=warehouse.GetIndexRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Index() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Index.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_index(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_index_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_index._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_index_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_index") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_index") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetIndexRequest.pb(warehouse.GetIndexRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Index.to_json(warehouse.Index()) + + request = warehouse.GetIndexRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Index() + + client.get_index(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_index_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetIndexRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_index(request) + + +def test_get_index_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Index() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Index.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_index(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/indexes/*}" % client.transport._host, args[1]) + + +def test_get_index_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_index( + warehouse.GetIndexRequest(), + name='name_value', + ) + + +def test_get_index_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListIndexesRequest, + dict, +]) +def test_list_indexes_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListIndexesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListIndexesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_indexes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIndexesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_indexes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_indexes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_indexes] = mock_rpc + + request = {} + client.list_indexes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_indexes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_indexes_rest_required_fields(request_type=warehouse.ListIndexesRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_indexes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_indexes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListIndexesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListIndexesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_indexes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_indexes_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_indexes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_indexes_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_indexes") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_indexes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListIndexesRequest.pb(warehouse.ListIndexesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListIndexesResponse.to_json(warehouse.ListIndexesResponse()) + + request = warehouse.ListIndexesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListIndexesResponse() + + client.list_indexes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_indexes_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListIndexesRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_indexes(request) + + +def test_list_indexes_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListIndexesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListIndexesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_indexes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/indexes" % client.transport._host, args[1]) + + +def test_list_indexes_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_indexes( + warehouse.ListIndexesRequest(), + parent='parent_value', + ) + + +def test_list_indexes_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + warehouse.Index(), + ], + next_page_token='abc', + ), + warehouse.ListIndexesResponse( + indexes=[], + next_page_token='def', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexesResponse( + indexes=[ + warehouse.Index(), + warehouse.Index(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListIndexesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_indexes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Index) + for i in results) + + pages = list(client.list_indexes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteIndexRequest, + dict, +]) +def test_delete_index_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_index(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_index_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_index] = mock_rpc + + request = {} + client.delete_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_index_rest_required_fields(request_type=warehouse.DeleteIndexRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_index(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_index_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_index._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_index_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_delete_index") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_index") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.DeleteIndexRequest.pb(warehouse.DeleteIndexRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.DeleteIndexRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_index(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_index_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteIndexRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_index(request) + + +def test_delete_index_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/indexes/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_index(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/indexes/*}" % client.transport._host, args[1]) + + +def test_delete_index_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_index( + warehouse.DeleteIndexRequest(), + name='name_value', + ) + + +def test_delete_index_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateCorpusRequest, + dict, +]) +def test_create_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["corpus"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'default_ttl': {'seconds': 751, 'nanos': 543}, 'type_': 1, 'search_capability_setting': {'search_capabilities': [{'type_': 1}]}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateCorpusRequest.meta.fields["corpus"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["corpus"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["corpus"][field])): + del request_init["corpus"][field][i][subfield] + else: + del request_init["corpus"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_corpus(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_corpus] = mock_rpc + + request = {} + client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_corpus_rest_required_fields(request_type=warehouse.CreateCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "corpus", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_corpus") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_corpus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateCorpusRequest.pb(warehouse.CreateCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.CreateCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_corpus(request) + + +def test_create_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/corpora" % client.transport._host, args[1]) + + +def test_create_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_corpus( + warehouse.CreateCorpusRequest(), + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + +def test_create_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetCorpusRequest, + dict, +]) +def test_get_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_corpus(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.type_ == warehouse.Corpus.Type.STREAM_VIDEO + +def test_get_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_corpus] = mock_rpc + + request = {} + client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_corpus_rest_required_fields(request_type=warehouse.GetCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_corpus") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_corpus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetCorpusRequest.pb(warehouse.GetCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Corpus.to_json(warehouse.Corpus()) + + request = warehouse.GetCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Corpus() + + client.get_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_corpus(request) + + +def test_get_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*}" % client.transport._host, args[1]) + + +def test_get_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_corpus( + warehouse.GetCorpusRequest(), + name='name_value', + ) + + +def test_get_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateCorpusRequest, + dict, +]) +def test_update_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': {'name': 'projects/sample1/locations/sample2/corpora/sample3'}} + request_init["corpus"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'default_ttl': {'seconds': 751, 'nanos': 543}, 'type_': 1, 'search_capability_setting': {'search_capabilities': [{'type_': 1}]}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateCorpusRequest.meta.fields["corpus"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["corpus"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["corpus"][field])): + del request_init["corpus"][field][i][subfield] + else: + del request_init["corpus"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + type_=warehouse.Corpus.Type.STREAM_VIDEO, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_corpus(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.type_ == warehouse.Corpus.Type.STREAM_VIDEO + +def test_update_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_corpus] = mock_rpc + + request = {} + client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_corpus_rest_required_fields(request_type=warehouse.UpdateCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_corpus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("corpus", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_corpus") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_corpus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateCorpusRequest.pb(warehouse.UpdateCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Corpus.to_json(warehouse.Corpus()) + + request = warehouse.UpdateCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Corpus() + + client.update_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': {'name': 'projects/sample1/locations/sample2/corpora/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_corpus(request) + + +def test_update_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + + # get arguments that satisfy an http rule for this method + sample_request = {'corpus': {'name': 'projects/sample1/locations/sample2/corpora/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{corpus.name=projects/*/locations/*/corpora/*}" % client.transport._host, args[1]) + + +def test_update_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_corpus( + warehouse.UpdateCorpusRequest(), + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListCorporaRequest, + dict, +]) +def test_list_corpora_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListCorporaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_corpora(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCorporaPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_corpora_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_corpora in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_corpora] = mock_rpc + + request = {} + client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_corpora(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_corpora_rest_required_fields(request_type=warehouse.ListCorporaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_corpora._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_corpora._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCorporaResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListCorporaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_corpora(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_corpora_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_corpora._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_corpora_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_corpora") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_corpora") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListCorporaRequest.pb(warehouse.ListCorporaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListCorporaResponse.to_json(warehouse.ListCorporaResponse()) + + request = warehouse.ListCorporaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListCorporaResponse() + + client.list_corpora(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_corpora_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListCorporaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_corpora(request) + + +def test_list_corpora_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCorporaResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListCorporaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_corpora(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/corpora" % client.transport._host, args[1]) + + +def test_list_corpora_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_corpora( + warehouse.ListCorporaRequest(), + parent='parent_value', + ) + + +def test_list_corpora_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListCorporaResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_corpora(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Corpus) + for i in results) + + pages = list(client.list_corpora(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteCorpusRequest, + dict, +]) +def test_delete_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_corpus(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_corpus] = mock_rpc + + request = {} + client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_corpus_rest_required_fields(request_type=warehouse.DeleteCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_corpus") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteCorpusRequest.pb(warehouse.DeleteCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_corpus(request) + + +def test_delete_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*}" % client.transport._host, args[1]) + + +def test_delete_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_corpus( + warehouse.DeleteCorpusRequest(), + name='name_value', + ) + + +def test_delete_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.AnalyzeCorpusRequest, + dict, +]) +def test_analyze_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.analyze_corpus(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_analyze_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.analyze_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.analyze_corpus] = mock_rpc + + request = {} + client.analyze_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.analyze_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_analyze_corpus_rest_required_fields(request_type=warehouse.AnalyzeCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.analyze_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_analyze_corpus") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_analyze_corpus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.AnalyzeCorpusRequest.pb(warehouse.AnalyzeCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.AnalyzeCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.analyze_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.AnalyzeCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_corpus(request) + + +def test_analyze_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateDataSchemaRequest, + dict, +]) +def test_create_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["data_schema"] = {'name': 'name_value', 'key': 'key_value', 'schema_details': {'type_': 1, 'proto_any_config': {'type_uri': 'type_uri_value'}, 'list_config': {'value_schema': {}}, 'customized_struct_config': {'field_schemas': {}}, 'granularity': 1, 'search_strategy': {'search_strategy_type': 1, 'confidence_score_index_config': {'field_path': 'field_path_value', 'threshold': 0.973}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateDataSchemaRequest.meta.fields["data_schema"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_schema"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_schema"][field])): + del request_init["data_schema"][field][i][subfield] + else: + del request_init["data_schema"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_data_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + +def test_create_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_schema] = mock_rpc + + request = {} + client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_data_schema_rest_required_fields(request_type=warehouse.CreateDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "dataSchema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_data_schema") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_data_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateDataSchemaRequest.pb(warehouse.CreateDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.DataSchema.to_json(warehouse.DataSchema()) + + request = warehouse.CreateDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.DataSchema() + + client.create_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_data_schema(request) + + +def test_create_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/dataSchemas" % client.transport._host, args[1]) + + +def test_create_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_data_schema( + warehouse.CreateDataSchemaRequest(), + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + +def test_create_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateDataSchemaRequest, + dict, +]) +def test_update_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_schema': {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'}} + request_init["data_schema"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4', 'key': 'key_value', 'schema_details': {'type_': 1, 'proto_any_config': {'type_uri': 'type_uri_value'}, 'list_config': {'value_schema': {}}, 'customized_struct_config': {'field_schemas': {}}, 'granularity': 1, 'search_strategy': {'search_strategy_type': 1, 'confidence_score_index_config': {'field_path': 'field_path_value', 'threshold': 0.973}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateDataSchemaRequest.meta.fields["data_schema"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_schema"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_schema"][field])): + del request_init["data_schema"][field][i][subfield] + else: + del request_init["data_schema"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + +def test_update_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_schema] = mock_rpc + + request = {} + client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_schema_rest_required_fields(request_type=warehouse.UpdateDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataSchema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_data_schema") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_data_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateDataSchemaRequest.pb(warehouse.UpdateDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.DataSchema.to_json(warehouse.DataSchema()) + + request = warehouse.UpdateDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.DataSchema() + + client.update_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_schema': {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_data_schema(request) + + +def test_update_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_schema': {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{data_schema.name=projects/*/locations/*/corpora/*/dataSchemas/*}" % client.transport._host, args[1]) + + +def test_update_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_schema( + warehouse.UpdateDataSchemaRequest(), + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetDataSchemaRequest, + dict, +]) +def test_get_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + +def test_get_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_schema] = mock_rpc + + request = {} + client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_schema_rest_required_fields(request_type=warehouse.GetDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_data_schema") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_data_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetDataSchemaRequest.pb(warehouse.GetDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.DataSchema.to_json(warehouse.DataSchema()) + + request = warehouse.GetDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.DataSchema() + + client.get_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_schema(request) + + +def test_get_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}" % client.transport._host, args[1]) + + +def test_get_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_schema( + warehouse.GetDataSchemaRequest(), + name='name_value', + ) + + +def test_get_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteDataSchemaRequest, + dict, +]) +def test_delete_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_data_schema(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_schema] = mock_rpc + + request = {} + client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_data_schema_rest_required_fields(request_type=warehouse.DeleteDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_data_schema") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteDataSchemaRequest.pb(warehouse.DeleteDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_data_schema(request) + + +def test_delete_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}" % client.transport._host, args[1]) + + +def test_delete_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_data_schema( + warehouse.DeleteDataSchemaRequest(), + name='name_value', + ) + + +def test_delete_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListDataSchemasRequest, + dict, +]) +def test_list_data_schemas_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListDataSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_data_schemas(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSchemasPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_data_schemas_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_schemas in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_schemas] = mock_rpc + + request = {} + client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_schemas_rest_required_fields(request_type=warehouse.ListDataSchemasRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_schemas._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_schemas._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListDataSchemasResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListDataSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_data_schemas(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_data_schemas_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_data_schemas._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_schemas_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_data_schemas") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_data_schemas") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListDataSchemasRequest.pb(warehouse.ListDataSchemasRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListDataSchemasResponse.to_json(warehouse.ListDataSchemasResponse()) + + request = warehouse.ListDataSchemasRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListDataSchemasResponse() + + client.list_data_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_data_schemas_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListDataSchemasRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_data_schemas(request) + + +def test_list_data_schemas_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListDataSchemasResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListDataSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_data_schemas(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/dataSchemas" % client.transport._host, args[1]) + + +def test_list_data_schemas_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_schemas( + warehouse.ListDataSchemasRequest(), + parent='parent_value', + ) + + +def test_list_data_schemas_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListDataSchemasResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_data_schemas(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.DataSchema) + for i in results) + + pages = list(client.list_data_schemas(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAnnotationRequest, + dict, +]) +def test_create_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request_init["annotation"] = {'name': 'name_value', 'user_specified_annotation': {'key': 'key_value', 'value': {'int_value': 967, 'float_value': 0.117, 'str_value': 'str_value_value', 'datetime_value': 'datetime_value_value', 'geo_coordinate': {'latitude': 0.86, 'longitude': 0.971}, 'proto_any_value': {'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}, 'bool_value': True, 'customized_struct_data_value': {'fields': {}}, 'list_value': {'values': {}}, 'customized_struct_value': {'elements': {}}}, 'partition': {'temporal_partition': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'spatial_partition': {'x_min': 539, 'y_min': 540, 'x_max': 541, 'y_max': 542}, 'relative_temporal_partition': {'start_offset': {'seconds': 751, 'nanos': 543}, 'end_offset': {}}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateAnnotationRequest.meta.fields["annotation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["annotation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["annotation"][field])): + del request_init["annotation"][field][i][subfield] + else: + del request_init["annotation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_annotation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + +def test_create_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_annotation] = mock_rpc + + request = {} + client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_annotation_rest_required_fields(request_type=warehouse.CreateAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_annotation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("annotation_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("annotationId", )) & set(("parent", "annotation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_annotation") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_annotation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateAnnotationRequest.pb(warehouse.CreateAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Annotation.to_json(warehouse.Annotation()) + + request = warehouse.CreateAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Annotation() + + client.create_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_annotation(request) + + +def test_create_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations" % client.transport._host, args[1]) + + +def test_create_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_annotation( + warehouse.CreateAnnotationRequest(), + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + +def test_create_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAnnotationRequest, + dict, +]) +def test_get_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_annotation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + +def test_get_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_annotation] = mock_rpc + + request = {} + client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_annotation_rest_required_fields(request_type=warehouse.GetAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_annotation") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_annotation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetAnnotationRequest.pb(warehouse.GetAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Annotation.to_json(warehouse.Annotation()) + + request = warehouse.GetAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Annotation() + + client.get_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_annotation(request) + + +def test_get_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}" % client.transport._host, args[1]) + + +def test_get_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_annotation( + warehouse.GetAnnotationRequest(), + name='name_value', + ) + + +def test_get_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAnnotationsRequest, + dict, +]) +def test_list_annotations_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAnnotationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_annotations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_annotations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_annotations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_annotations] = mock_rpc + + request = {} + client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_annotations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_annotations_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_annotations") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_annotations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListAnnotationsRequest.pb(warehouse.ListAnnotationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListAnnotationsResponse.to_json(warehouse.ListAnnotationsResponse()) + + request = warehouse.ListAnnotationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListAnnotationsResponse() + + client.list_annotations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_annotations_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListAnnotationsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_annotations(request) + + +def test_list_annotations_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAnnotationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAnnotationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_annotations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations" % client.transport._host, args[1]) + + +def test_list_annotations_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_annotations( + warehouse.ListAnnotationsRequest(), + parent='parent_value', + ) + + +def test_list_annotations_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListAnnotationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + pager = client.list_annotations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Annotation) + for i in results) + + pages = list(client.list_annotations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAnnotationRequest, + dict, +]) +def test_update_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'annotation': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'}} + request_init["annotation"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5', 'user_specified_annotation': {'key': 'key_value', 'value': {'int_value': 967, 'float_value': 0.117, 'str_value': 'str_value_value', 'datetime_value': 'datetime_value_value', 'geo_coordinate': {'latitude': 0.86, 'longitude': 0.971}, 'proto_any_value': {'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}, 'bool_value': True, 'customized_struct_data_value': {'fields': {}}, 'list_value': {'values': {}}, 'customized_struct_value': {'elements': {}}}, 'partition': {'temporal_partition': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'spatial_partition': {'x_min': 539, 'y_min': 540, 'x_max': 541, 'y_max': 542}, 'relative_temporal_partition': {'start_offset': {'seconds': 751, 'nanos': 543}, 'end_offset': {}}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateAnnotationRequest.meta.fields["annotation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["annotation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["annotation"][field])): + del request_init["annotation"][field][i][subfield] + else: + del request_init["annotation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_annotation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + +def test_update_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_annotation] = mock_rpc + + request = {} + client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_annotation_rest_required_fields(request_type=warehouse.UpdateAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_annotation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("annotation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_annotation") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_annotation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateAnnotationRequest.pb(warehouse.UpdateAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Annotation.to_json(warehouse.Annotation()) + + request = warehouse.UpdateAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Annotation() + + client.update_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'annotation': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_annotation(request) + + +def test_update_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + + # get arguments that satisfy an http rule for this method + sample_request = {'annotation': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{annotation.name=projects/*/locations/*/corpora/*/assets/*/annotations/*}" % client.transport._host, args[1]) + + +def test_update_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_annotation( + warehouse.UpdateAnnotationRequest(), + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAnnotationRequest, + dict, +]) +def test_delete_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_annotation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_annotation] = mock_rpc + + request = {} + client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_annotation_rest_required_fields(request_type=warehouse.DeleteAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_annotation") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteAnnotationRequest.pb(warehouse.DeleteAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_annotation(request) + + +def test_delete_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}" % client.transport._host, args[1]) + + +def test_delete_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_annotation( + warehouse.DeleteAnnotationRequest(), + name='name_value', + ) + + +def test_delete_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_ingest_asset_rest_no_http_options(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = warehouse.IngestAssetRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.ingest_asset(requests) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ClipAssetRequest, + dict, +]) +def test_clip_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ClipAssetResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ClipAssetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.clip_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.ClipAssetResponse) + +def test_clip_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clip_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clip_asset] = mock_rpc + + request = {} + client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.clip_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_clip_asset_rest_required_fields(request_type=warehouse.ClipAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clip_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clip_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ClipAssetResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ClipAssetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.clip_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_clip_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.clip_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "temporalPartition", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_clip_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_clip_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_clip_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ClipAssetRequest.pb(warehouse.ClipAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ClipAssetResponse.to_json(warehouse.ClipAssetResponse()) + + request = warehouse.ClipAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ClipAssetResponse() + + client.clip_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_clip_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.ClipAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.clip_asset(request) + + +def test_clip_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GenerateHlsUriRequest, + dict, +]) +def test_generate_hls_uri_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.GenerateHlsUriResponse( + uri='uri_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.GenerateHlsUriResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_hls_uri(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateHlsUriResponse) + assert response.uri == 'uri_value' + +def test_generate_hls_uri_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_hls_uri in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_hls_uri] = mock_rpc + + request = {} + client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_hls_uri(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_hls_uri_rest_required_fields(request_type=warehouse.GenerateHlsUriRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_hls_uri._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_hls_uri._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.GenerateHlsUriResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.GenerateHlsUriResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.generate_hls_uri(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_hls_uri_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_hls_uri._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_hls_uri_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_generate_hls_uri") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_generate_hls_uri") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GenerateHlsUriRequest.pb(warehouse.GenerateHlsUriRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.GenerateHlsUriResponse.to_json(warehouse.GenerateHlsUriResponse()) + + request = warehouse.GenerateHlsUriRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.GenerateHlsUriResponse() + + client.generate_hls_uri(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_hls_uri_rest_bad_request(transport: str = 'rest', request_type=warehouse.GenerateHlsUriRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_hls_uri(request) + + +def test_generate_hls_uri_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ImportAssetsRequest, + dict, +]) +def test_import_assets_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_assets(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_import_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_assets] = mock_rpc + + request = {} + client.import_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_assets_rest_required_fields(request_type=warehouse.ImportAssetsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_assets_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_assets_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_import_assets") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_import_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ImportAssetsRequest.pb(warehouse.ImportAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.ImportAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_assets_rest_bad_request(transport: str = 'rest', request_type=warehouse.ImportAssetsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_assets(request) + + +def test_import_assets_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateSearchConfigRequest, + dict, +]) +def test_create_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["search_config"] = {'name': 'name_value', 'facet_property': {'fixed_range_bucket_spec': {'bucket_start': {'string_value': 'string_value_value', 'integer_value': 1386, 'datetime_value': {'year': 433, 'month': 550, 'day': 318, 'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543, 'utc_offset': {'seconds': 751, 'nanos': 543}, 'time_zone': {'id': 'id_value', 'version': 'version_value'}}}, 'bucket_granularity': {}, 'bucket_count': 1286}, 'custom_range_bucket_spec': {'endpoints': {}}, 'datetime_bucket_spec': {'granularity': 1}, 'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2'], 'display_name': 'display_name_value', 'result_size': 1209, 'bucket_type': 1}, 'search_criteria_property': {'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2']}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateSearchConfigRequest.meta.fields["search_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_config"][field])): + del request_init["search_config"][field][i][subfield] + else: + del request_init["search_config"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_search_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + +def test_create_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_config] = mock_rpc + + request = {} + client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_search_config_rest_required_fields(request_type=warehouse.CreateSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["search_config_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "searchConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "searchConfigId" in jsonified_request + assert jsonified_request["searchConfigId"] == request_init["search_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["searchConfigId"] = 'search_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("search_config_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "searchConfigId" in jsonified_request + assert jsonified_request["searchConfigId"] == 'search_config_id_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_search_config(request) + + expected_params = [ + ( + "searchConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("searchConfigId", )) & set(("parent", "searchConfig", "searchConfigId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_search_config") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_search_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateSearchConfigRequest.pb(warehouse.CreateSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchConfig.to_json(warehouse.SearchConfig()) + + request = warehouse.CreateSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchConfig() + + client.create_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_search_config(request) + + +def test_create_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/searchConfigs" % client.transport._host, args[1]) + + +def test_create_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_search_config( + warehouse.CreateSearchConfigRequest(), + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + +def test_create_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateSearchConfigRequest, + dict, +]) +def test_update_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'search_config': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'}} + request_init["search_config"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4', 'facet_property': {'fixed_range_bucket_spec': {'bucket_start': {'string_value': 'string_value_value', 'integer_value': 1386, 'datetime_value': {'year': 433, 'month': 550, 'day': 318, 'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543, 'utc_offset': {'seconds': 751, 'nanos': 543}, 'time_zone': {'id': 'id_value', 'version': 'version_value'}}}, 'bucket_granularity': {}, 'bucket_count': 1286}, 'custom_range_bucket_spec': {'endpoints': {}}, 'datetime_bucket_spec': {'granularity': 1}, 'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2'], 'display_name': 'display_name_value', 'result_size': 1209, 'bucket_type': 1}, 'search_criteria_property': {'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2']}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateSearchConfigRequest.meta.fields["search_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_config"][field])): + del request_init["search_config"][field][i][subfield] + else: + del request_init["search_config"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_search_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + +def test_update_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_config] = mock_rpc + + request = {} + client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_search_config_rest_required_fields(request_type=warehouse.UpdateSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_search_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("searchConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_search_config") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_search_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateSearchConfigRequest.pb(warehouse.UpdateSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchConfig.to_json(warehouse.SearchConfig()) + + request = warehouse.UpdateSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchConfig() + + client.update_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'search_config': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_search_config(request) + + +def test_update_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'search_config': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{search_config.name=projects/*/locations/*/corpora/*/searchConfigs/*}" % client.transport._host, args[1]) + + +def test_update_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_search_config( + warehouse.UpdateSearchConfigRequest(), + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetSearchConfigRequest, + dict, +]) +def test_get_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_search_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + +def test_get_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_config] = mock_rpc + + request = {} + client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_search_config_rest_required_fields(request_type=warehouse.GetSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_search_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_search_config") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_search_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetSearchConfigRequest.pb(warehouse.GetSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchConfig.to_json(warehouse.SearchConfig()) + + request = warehouse.GetSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchConfig() + + client.get_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_search_config(request) + + +def test_get_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}" % client.transport._host, args[1]) + + +def test_get_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_search_config( + warehouse.GetSearchConfigRequest(), + name='name_value', + ) + + +def test_get_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteSearchConfigRequest, + dict, +]) +def test_delete_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_search_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_config] = mock_rpc + + request = {} + client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_search_config_rest_required_fields(request_type=warehouse.DeleteSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_search_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_search_config") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteSearchConfigRequest.pb(warehouse.DeleteSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_search_config(request) + + +def test_delete_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_search_config( + warehouse.DeleteSearchConfigRequest(), + name='name_value', + ) + + +def test_delete_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListSearchConfigsRequest, + dict, +]) +def test_list_search_configs_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListSearchConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_search_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_search_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_configs] = mock_rpc + + request = {} + client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_search_configs_rest_required_fields(request_type=warehouse.ListSearchConfigsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListSearchConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_search_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_search_configs_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_search_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_search_configs_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_search_configs") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_search_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListSearchConfigsRequest.pb(warehouse.ListSearchConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListSearchConfigsResponse.to_json(warehouse.ListSearchConfigsResponse()) + + request = warehouse.ListSearchConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListSearchConfigsResponse() + + client.list_search_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_search_configs_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListSearchConfigsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_search_configs(request) + + +def test_list_search_configs_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListSearchConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_search_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/searchConfigs" % client.transport._host, args[1]) + + +def test_list_search_configs_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_search_configs( + warehouse.ListSearchConfigsRequest(), + parent='parent_value', + ) + + +def test_list_search_configs_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListSearchConfigsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_search_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchConfig) + for i in results) + + pages = list(client.list_search_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateSearchHypernymRequest, + dict, +]) +def test_create_search_hypernym_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["search_hypernym"] = {'name': 'name_value', 'hypernym': 'hypernym_value', 'hyponyms': ['hyponyms_value1', 'hyponyms_value2']} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateSearchHypernymRequest.meta.fields["search_hypernym"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_hypernym"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_hypernym"][field])): + del request_init["search_hypernym"][field][i][subfield] + else: + del request_init["search_hypernym"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_search_hypernym(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + +def test_create_search_hypernym_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_hypernym] = mock_rpc + + request = {} + client.create_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_search_hypernym_rest_required_fields(request_type=warehouse.CreateSearchHypernymRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_hypernym._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_hypernym._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("search_hypernym_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_search_hypernym(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_search_hypernym_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_search_hypernym._get_unset_required_fields({}) + assert set(unset_fields) == (set(("searchHypernymId", )) & set(("parent", "searchHypernym", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_search_hypernym_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_search_hypernym") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_search_hypernym") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateSearchHypernymRequest.pb(warehouse.CreateSearchHypernymRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchHypernym.to_json(warehouse.SearchHypernym()) + + request = warehouse.CreateSearchHypernymRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchHypernym() + + client.create_search_hypernym(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_search_hypernym_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateSearchHypernymRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_search_hypernym(request) + + +def test_create_search_hypernym_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + search_hypernym=warehouse.SearchHypernym(name='name_value'), + search_hypernym_id='search_hypernym_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_search_hypernym(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/searchHypernyms" % client.transport._host, args[1]) + + +def test_create_search_hypernym_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_search_hypernym( + warehouse.CreateSearchHypernymRequest(), + parent='parent_value', + search_hypernym=warehouse.SearchHypernym(name='name_value'), + search_hypernym_id='search_hypernym_id_value', + ) + + +def test_create_search_hypernym_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateSearchHypernymRequest, + dict, +]) +def test_update_search_hypernym_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'search_hypernym': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'}} + request_init["search_hypernym"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4', 'hypernym': 'hypernym_value', 'hyponyms': ['hyponyms_value1', 'hyponyms_value2']} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateSearchHypernymRequest.meta.fields["search_hypernym"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_hypernym"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_hypernym"][field])): + del request_init["search_hypernym"][field][i][subfield] + else: + del request_init["search_hypernym"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_search_hypernym(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + +def test_update_search_hypernym_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_hypernym] = mock_rpc + + request = {} + client.update_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_search_hypernym_rest_required_fields(request_type=warehouse.UpdateSearchHypernymRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_hypernym._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_hypernym._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_search_hypernym(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_search_hypernym_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_search_hypernym._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("searchHypernym", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_search_hypernym_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_search_hypernym") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_search_hypernym") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateSearchHypernymRequest.pb(warehouse.UpdateSearchHypernymRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchHypernym.to_json(warehouse.SearchHypernym()) + + request = warehouse.UpdateSearchHypernymRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchHypernym() + + client.update_search_hypernym(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_search_hypernym_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateSearchHypernymRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'search_hypernym': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_search_hypernym(request) + + +def test_update_search_hypernym_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym() + + # get arguments that satisfy an http rule for this method + sample_request = {'search_hypernym': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + search_hypernym=warehouse.SearchHypernym(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_search_hypernym(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{search_hypernym.name=projects/*/locations/*/corpora/*/searchHypernyms/*}" % client.transport._host, args[1]) + + +def test_update_search_hypernym_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_search_hypernym( + warehouse.UpdateSearchHypernymRequest(), + search_hypernym=warehouse.SearchHypernym(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_search_hypernym_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetSearchHypernymRequest, + dict, +]) +def test_get_search_hypernym_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym( + name='name_value', + hypernym='hypernym_value', + hyponyms=['hyponyms_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_search_hypernym(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchHypernym) + assert response.name == 'name_value' + assert response.hypernym == 'hypernym_value' + assert response.hyponyms == ['hyponyms_value'] + +def test_get_search_hypernym_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_hypernym] = mock_rpc + + request = {} + client.get_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_search_hypernym_rest_required_fields(request_type=warehouse.GetSearchHypernymRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_hypernym._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_hypernym._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_search_hypernym(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_search_hypernym_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_search_hypernym._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_search_hypernym_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_search_hypernym") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_search_hypernym") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetSearchHypernymRequest.pb(warehouse.GetSearchHypernymRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchHypernym.to_json(warehouse.SearchHypernym()) + + request = warehouse.GetSearchHypernymRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchHypernym() + + client.get_search_hypernym(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_search_hypernym_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetSearchHypernymRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_search_hypernym(request) + + +def test_get_search_hypernym_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchHypernym() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchHypernym.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_search_hypernym(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/searchHypernyms/*}" % client.transport._host, args[1]) + + +def test_get_search_hypernym_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_search_hypernym( + warehouse.GetSearchHypernymRequest(), + name='name_value', + ) + + +def test_get_search_hypernym_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteSearchHypernymRequest, + dict, +]) +def test_delete_search_hypernym_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_search_hypernym(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_search_hypernym_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_hypernym in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_hypernym] = mock_rpc + + request = {} + client.delete_search_hypernym(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_hypernym(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_search_hypernym_rest_required_fields(request_type=warehouse.DeleteSearchHypernymRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_hypernym._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_hypernym._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_search_hypernym(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_search_hypernym_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_search_hypernym._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_search_hypernym_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_search_hypernym") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteSearchHypernymRequest.pb(warehouse.DeleteSearchHypernymRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteSearchHypernymRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_search_hypernym(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_search_hypernym_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteSearchHypernymRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_search_hypernym(request) + + +def test_delete_search_hypernym_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchHypernyms/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_search_hypernym(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/searchHypernyms/*}" % client.transport._host, args[1]) + + +def test_delete_search_hypernym_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_search_hypernym( + warehouse.DeleteSearchHypernymRequest(), + name='name_value', + ) + + +def test_delete_search_hypernym_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListSearchHypernymsRequest, + dict, +]) +def test_list_search_hypernyms_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchHypernymsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListSearchHypernymsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_search_hypernyms(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchHypernymsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_search_hypernyms_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_hypernyms in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_hypernyms] = mock_rpc + + request = {} + client.list_search_hypernyms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_hypernyms(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_search_hypernyms_rest_required_fields(request_type=warehouse.ListSearchHypernymsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_hypernyms._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_hypernyms._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchHypernymsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListSearchHypernymsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_search_hypernyms(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_search_hypernyms_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_search_hypernyms._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_search_hypernyms_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_search_hypernyms") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_search_hypernyms") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListSearchHypernymsRequest.pb(warehouse.ListSearchHypernymsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListSearchHypernymsResponse.to_json(warehouse.ListSearchHypernymsResponse()) + + request = warehouse.ListSearchHypernymsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListSearchHypernymsResponse() + + client.list_search_hypernyms(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_search_hypernyms_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListSearchHypernymsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_search_hypernyms(request) + + +def test_list_search_hypernyms_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchHypernymsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListSearchHypernymsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_search_hypernyms(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/searchHypernyms" % client.transport._host, args[1]) + + +def test_list_search_hypernyms_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_search_hypernyms( + warehouse.ListSearchHypernymsRequest(), + parent='parent_value', + ) + + +def test_list_search_hypernyms_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + next_page_token='abc', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[], + next_page_token='def', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchHypernymsResponse( + search_hypernyms=[ + warehouse.SearchHypernym(), + warehouse.SearchHypernym(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListSearchHypernymsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_search_hypernyms(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchHypernym) + for i in results) + + pages = list(client.list_search_hypernyms(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.SearchAssetsRequest, + dict, +]) +def test_search_assets_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAssetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_search_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_assets] = mock_rpc + + request = {} + client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_search_assets_rest_required_fields(request_type=warehouse.SearchAssetsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["corpus"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["corpus"] = 'corpus_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "corpus" in jsonified_request + assert jsonified_request["corpus"] == 'corpus_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_assets_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("corpus", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_assets_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_search_assets") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_search_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.SearchAssetsRequest.pb(warehouse.SearchAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchAssetsResponse.to_json(warehouse.SearchAssetsResponse()) + + request = warehouse.SearchAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchAssetsResponse() + + client.search_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_assets_rest_bad_request(transport: str = 'rest', request_type=warehouse.SearchAssetsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_assets(request) + + +def test_search_assets_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.SearchAssetsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'corpus': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.search_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in results) + + pages = list(client.search_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.SearchIndexEndpointRequest, + dict, +]) +def test_search_index_endpoint_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchIndexEndpointResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchIndexEndpointResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_index_endpoint(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchIndexEndpointPager) + assert response.next_page_token == 'next_page_token_value' + +def test_search_index_endpoint_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_index_endpoint] = mock_rpc + + request = {} + client.search_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_search_index_endpoint_rest_required_fields(request_type=warehouse.SearchIndexEndpointRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["index_endpoint"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["indexEndpoint"] = 'index_endpoint_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "indexEndpoint" in jsonified_request + assert jsonified_request["indexEndpoint"] == 'index_endpoint_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchIndexEndpointResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchIndexEndpointResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_index_endpoint(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_index_endpoint_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_index_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("indexEndpoint", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_index_endpoint_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_search_index_endpoint") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_search_index_endpoint") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.SearchIndexEndpointRequest.pb(warehouse.SearchIndexEndpointRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchIndexEndpointResponse.to_json(warehouse.SearchIndexEndpointResponse()) + + request = warehouse.SearchIndexEndpointRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchIndexEndpointResponse() + + client.search_index_endpoint(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_index_endpoint_rest_bad_request(transport: str = 'rest', request_type=warehouse.SearchIndexEndpointRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_index_endpoint(request) + + +def test_search_index_endpoint_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchIndexEndpointResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.SearchIndexEndpointResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'index_endpoint': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + + pager = client.search_index_endpoint(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in results) + + pages = list(client.search_index_endpoint(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateIndexEndpointRequest, + dict, +]) +def test_create_index_endpoint_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["index_endpoint"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'deployed_index': {'index': 'index_value'}, 'state': 1, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateIndexEndpointRequest.meta.fields["index_endpoint"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["index_endpoint"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["index_endpoint"][field])): + del request_init["index_endpoint"][field][i][subfield] + else: + del request_init["index_endpoint"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_index_endpoint(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_index_endpoint_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_index_endpoint] = mock_rpc + + request = {} + client.create_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_index_endpoint_rest_required_fields(request_type=warehouse.CreateIndexEndpointRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_index_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("index_endpoint_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_index_endpoint(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_index_endpoint_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_index_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == (set(("indexEndpointId", )) & set(("parent", "indexEndpoint", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_index_endpoint_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_index_endpoint") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_index_endpoint") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateIndexEndpointRequest.pb(warehouse.CreateIndexEndpointRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.CreateIndexEndpointRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_index_endpoint(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_index_endpoint_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateIndexEndpointRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_index_endpoint(request) + + +def test_create_index_endpoint_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + index_endpoint_id='index_endpoint_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_index_endpoint(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/indexEndpoints" % client.transport._host, args[1]) + + +def test_create_index_endpoint_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_index_endpoint( + warehouse.CreateIndexEndpointRequest(), + parent='parent_value', + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + index_endpoint_id='index_endpoint_id_value', + ) + + +def test_create_index_endpoint_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetIndexEndpointRequest, + dict, +]) +def test_get_index_endpoint_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.IndexEndpoint( + name='name_value', + display_name='display_name_value', + description='description_value', + state=warehouse.IndexEndpoint.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.IndexEndpoint.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_index_endpoint(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.IndexEndpoint) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == warehouse.IndexEndpoint.State.CREATING + +def test_get_index_endpoint_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_index_endpoint] = mock_rpc + + request = {} + client.get_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_index_endpoint_rest_required_fields(request_type=warehouse.GetIndexEndpointRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.IndexEndpoint() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.IndexEndpoint.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_index_endpoint(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_index_endpoint_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_index_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_index_endpoint_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_index_endpoint") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_index_endpoint") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetIndexEndpointRequest.pb(warehouse.GetIndexEndpointRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.IndexEndpoint.to_json(warehouse.IndexEndpoint()) + + request = warehouse.GetIndexEndpointRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.IndexEndpoint() + + client.get_index_endpoint(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_index_endpoint_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetIndexEndpointRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_index_endpoint(request) + + +def test_get_index_endpoint_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.IndexEndpoint() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.IndexEndpoint.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_index_endpoint(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/indexEndpoints/*}" % client.transport._host, args[1]) + + +def test_get_index_endpoint_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_index_endpoint( + warehouse.GetIndexEndpointRequest(), + name='name_value', + ) + + +def test_get_index_endpoint_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListIndexEndpointsRequest, + dict, +]) +def test_list_index_endpoints_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListIndexEndpointsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListIndexEndpointsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_index_endpoints(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIndexEndpointsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_index_endpoints_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_index_endpoints in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_index_endpoints] = mock_rpc + + request = {} + client.list_index_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_index_endpoints(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_index_endpoints_rest_required_fields(request_type=warehouse.ListIndexEndpointsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_index_endpoints._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_index_endpoints._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListIndexEndpointsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListIndexEndpointsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_index_endpoints(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_index_endpoints_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_index_endpoints._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_index_endpoints_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_index_endpoints") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_index_endpoints") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListIndexEndpointsRequest.pb(warehouse.ListIndexEndpointsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListIndexEndpointsResponse.to_json(warehouse.ListIndexEndpointsResponse()) + + request = warehouse.ListIndexEndpointsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListIndexEndpointsResponse() + + client.list_index_endpoints(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_index_endpoints_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListIndexEndpointsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_index_endpoints(request) + + +def test_list_index_endpoints_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListIndexEndpointsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListIndexEndpointsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_index_endpoints(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/indexEndpoints" % client.transport._host, args[1]) + + +def test_list_index_endpoints_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_index_endpoints( + warehouse.ListIndexEndpointsRequest(), + parent='parent_value', + ) + + +def test_list_index_endpoints_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + next_page_token='abc', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[], + next_page_token='def', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + ], + next_page_token='ghi', + ), + warehouse.ListIndexEndpointsResponse( + index_endpoints=[ + warehouse.IndexEndpoint(), + warehouse.IndexEndpoint(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListIndexEndpointsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_index_endpoints(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.IndexEndpoint) + for i in results) + + pages = list(client.list_index_endpoints(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateIndexEndpointRequest, + dict, +]) +def test_update_index_endpoint_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'}} + request_init["index_endpoint"] = {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'deployed_index': {'index': 'index_value'}, 'state': 1, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateIndexEndpointRequest.meta.fields["index_endpoint"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["index_endpoint"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["index_endpoint"][field])): + del request_init["index_endpoint"][field][i][subfield] + else: + del request_init["index_endpoint"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_index_endpoint(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_index_endpoint_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_index_endpoint] = mock_rpc + + request = {} + client.update_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_index_endpoint_rest_required_fields(request_type=warehouse.UpdateIndexEndpointRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_index_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_index_endpoint(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_index_endpoint_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_index_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("indexEndpoint", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_index_endpoint_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_index_endpoint") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_index_endpoint") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateIndexEndpointRequest.pb(warehouse.UpdateIndexEndpointRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.UpdateIndexEndpointRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_index_endpoint(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_index_endpoint_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateIndexEndpointRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_index_endpoint(request) + + +def test_update_index_endpoint_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'index_endpoint': {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_index_endpoint(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{index_endpoint.name=projects/*/locations/*/indexEndpoints/*}" % client.transport._host, args[1]) + + +def test_update_index_endpoint_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_index_endpoint( + warehouse.UpdateIndexEndpointRequest(), + index_endpoint=warehouse.IndexEndpoint(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_index_endpoint_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteIndexEndpointRequest, + dict, +]) +def test_delete_index_endpoint_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_index_endpoint(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_index_endpoint_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_index_endpoint in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_index_endpoint] = mock_rpc + + request = {} + client.delete_index_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_index_endpoint(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_index_endpoint_rest_required_fields(request_type=warehouse.DeleteIndexEndpointRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_index_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_index_endpoint(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_index_endpoint_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_index_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_index_endpoint_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_delete_index_endpoint") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_index_endpoint") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.DeleteIndexEndpointRequest.pb(warehouse.DeleteIndexEndpointRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.DeleteIndexEndpointRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_index_endpoint(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_index_endpoint_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteIndexEndpointRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_index_endpoint(request) + + +def test_delete_index_endpoint_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_index_endpoint(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/indexEndpoints/*}" % client.transport._host, args[1]) + + +def test_delete_index_endpoint_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_index_endpoint( + warehouse.DeleteIndexEndpointRequest(), + name='name_value', + ) + + +def test_delete_index_endpoint_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeployIndexRequest, + dict, +]) +def test_deploy_index_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.deploy_index(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_deploy_index_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.deploy_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.deploy_index] = mock_rpc + + request = {} + client.deploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.deploy_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_deploy_index_rest_required_fields(request_type=warehouse.DeployIndexRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["index_endpoint"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["indexEndpoint"] = 'index_endpoint_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "indexEndpoint" in jsonified_request + assert jsonified_request["indexEndpoint"] == 'index_endpoint_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.deploy_index(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_deploy_index_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.deploy_index._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("indexEndpoint", "deployedIndex", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_deploy_index_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_deploy_index") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_deploy_index") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.DeployIndexRequest.pb(warehouse.DeployIndexRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.DeployIndexRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.deploy_index(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_deploy_index_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeployIndexRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.deploy_index(request) + + +def test_deploy_index_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UndeployIndexRequest, + dict, +]) +def test_undeploy_index_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.undeploy_index(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_undeploy_index_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.undeploy_index in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undeploy_index] = mock_rpc + + request = {} + client.undeploy_index(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.undeploy_index(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_undeploy_index_rest_required_fields(request_type=warehouse.UndeployIndexRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["index_endpoint"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["indexEndpoint"] = 'index_endpoint_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_index._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "indexEndpoint" in jsonified_request + assert jsonified_request["indexEndpoint"] == 'index_endpoint_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.undeploy_index(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undeploy_index_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undeploy_index._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("indexEndpoint", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undeploy_index_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_undeploy_index") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_undeploy_index") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UndeployIndexRequest.pb(warehouse.UndeployIndexRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.UndeployIndexRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undeploy_index(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undeploy_index_rest_bad_request(transport: str = 'rest', request_type=warehouse.UndeployIndexRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'index_endpoint': 'projects/sample1/locations/sample2/indexEndpoints/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undeploy_index(request) + + +def test_undeploy_index_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateCollectionRequest, + dict, +]) +def test_create_collection_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["collection"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateCollectionRequest.meta.fields["collection"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["collection"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["collection"][field])): + del request_init["collection"][field][i][subfield] + else: + del request_init["collection"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_collection(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_collection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_collection] = mock_rpc + + request = {} + client.create_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_collection_rest_required_fields(request_type=warehouse.CreateCollectionRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_collection._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("collection_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_collection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_collection_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(("collectionId", )) & set(("parent", "collection", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_collection_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_collection") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_collection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateCollectionRequest.pb(warehouse.CreateCollectionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.CreateCollectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_collection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_collection_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateCollectionRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_collection(request) + + +def test_create_collection_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + collection=warehouse.Collection(name='name_value'), + collection_id='collection_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_collection(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/collections" % client.transport._host, args[1]) + + +def test_create_collection_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_collection( + warehouse.CreateCollectionRequest(), + parent='parent_value', + collection=warehouse.Collection(name='name_value'), + collection_id='collection_id_value', + ) + + +def test_create_collection_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteCollectionRequest, + dict, +]) +def test_delete_collection_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_collection(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_collection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_collection] = mock_rpc + + request = {} + client.delete_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_collection_rest_required_fields(request_type=warehouse.DeleteCollectionRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_collection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_collection_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_collection_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_delete_collection") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_collection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.DeleteCollectionRequest.pb(warehouse.DeleteCollectionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.DeleteCollectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_collection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_collection_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteCollectionRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_collection(request) + + +def test_delete_collection_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_collection(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/collections/*}" % client.transport._host, args[1]) + + +def test_delete_collection_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_collection( + warehouse.DeleteCollectionRequest(), + name='name_value', + ) + + +def test_delete_collection_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetCollectionRequest, + dict, +]) +def test_get_collection_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Collection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_collection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Collection) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_collection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_collection] = mock_rpc + + request = {} + client.get_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_collection_rest_required_fields(request_type=warehouse.GetCollectionRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Collection() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Collection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_collection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_collection_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_collection_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_collection") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_collection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetCollectionRequest.pb(warehouse.GetCollectionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Collection.to_json(warehouse.Collection()) + + request = warehouse.GetCollectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Collection() + + client.get_collection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_collection_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetCollectionRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_collection(request) + + +def test_get_collection_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Collection() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Collection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_collection(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/corpora/*/collections/*}" % client.transport._host, args[1]) + + +def test_get_collection_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_collection( + warehouse.GetCollectionRequest(), + name='name_value', + ) + + +def test_get_collection_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateCollectionRequest, + dict, +]) +def test_update_collection_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'collection': {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + request_init["collection"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4', 'display_name': 'display_name_value', 'description': 'description_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateCollectionRequest.meta.fields["collection"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["collection"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["collection"][field])): + del request_init["collection"][field][i][subfield] + else: + del request_init["collection"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Collection( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Collection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_collection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Collection) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_update_collection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_collection] = mock_rpc + + request = {} + client.update_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_collection_rest_required_fields(request_type=warehouse.UpdateCollectionRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_collection._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Collection() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Collection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_collection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_collection_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("collection", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_collection_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_collection") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_collection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateCollectionRequest.pb(warehouse.UpdateCollectionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Collection.to_json(warehouse.Collection()) + + request = warehouse.UpdateCollectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Collection() + + client.update_collection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_collection_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateCollectionRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'collection': {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_collection(request) + + +def test_update_collection_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Collection() + + # get arguments that satisfy an http rule for this method + sample_request = {'collection': {'name': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + collection=warehouse.Collection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Collection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_collection(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{collection.name=projects/*/locations/*/corpora/*/collections/*}" % client.transport._host, args[1]) + + +def test_update_collection_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_collection( + warehouse.UpdateCollectionRequest(), + collection=warehouse.Collection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_collection_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListCollectionsRequest, + dict, +]) +def test_list_collections_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCollectionsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListCollectionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_collections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCollectionsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_collections_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_collections in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_collections] = mock_rpc + + request = {} + client.list_collections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_collections(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_collections_rest_required_fields(request_type=warehouse.ListCollectionsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_collections._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_collections._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCollectionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListCollectionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_collections(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_collections_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_collections._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_collections_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_collections") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_collections") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListCollectionsRequest.pb(warehouse.ListCollectionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListCollectionsResponse.to_json(warehouse.ListCollectionsResponse()) + + request = warehouse.ListCollectionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListCollectionsResponse() + + client.list_collections(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_collections_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListCollectionsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_collections(request) + + +def test_list_collections_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCollectionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListCollectionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_collections(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/corpora/*}/collections" % client.transport._host, args[1]) + + +def test_list_collections_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_collections( + warehouse.ListCollectionsRequest(), + parent='parent_value', + ) + + +def test_list_collections_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + warehouse.Collection(), + ], + next_page_token='abc', + ), + warehouse.ListCollectionsResponse( + collections=[], + next_page_token='def', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + ], + next_page_token='ghi', + ), + warehouse.ListCollectionsResponse( + collections=[ + warehouse.Collection(), + warehouse.Collection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListCollectionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_collections(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Collection) + for i in results) + + pages = list(client.list_collections(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.AddCollectionItemRequest, + dict, +]) +def test_add_collection_item_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'item': {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.AddCollectionItemResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.AddCollectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.add_collection_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.AddCollectionItemResponse) + +def test_add_collection_item_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_collection_item in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_collection_item] = mock_rpc + + request = {} + client.add_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.add_collection_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_add_collection_item_rest_required_fields(request_type=warehouse.AddCollectionItemRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_collection_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_collection_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.AddCollectionItemResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.AddCollectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.add_collection_item(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_add_collection_item_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.add_collection_item._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("item", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_collection_item_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_add_collection_item") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_add_collection_item") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.AddCollectionItemRequest.pb(warehouse.AddCollectionItemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.AddCollectionItemResponse.to_json(warehouse.AddCollectionItemResponse()) + + request = warehouse.AddCollectionItemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.AddCollectionItemResponse() + + client.add_collection_item(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_collection_item_rest_bad_request(transport: str = 'rest', request_type=warehouse.AddCollectionItemRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'item': {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.add_collection_item(request) + + +def test_add_collection_item_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.AddCollectionItemResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'item': {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + item=warehouse.CollectionItem(collection='collection_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.AddCollectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.add_collection_item(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{item.collection=projects/*/locations/*/corpora/*/collections/*}:addCollectionItem" % client.transport._host, args[1]) + + +def test_add_collection_item_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_collection_item( + warehouse.AddCollectionItemRequest(), + item=warehouse.CollectionItem(collection='collection_value'), + ) + + +def test_add_collection_item_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.RemoveCollectionItemRequest, + dict, +]) +def test_remove_collection_item_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'item': {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.RemoveCollectionItemResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.RemoveCollectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.remove_collection_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.RemoveCollectionItemResponse) + +def test_remove_collection_item_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_collection_item in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_collection_item] = mock_rpc + + request = {} + client.remove_collection_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.remove_collection_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_collection_item_rest_required_fields(request_type=warehouse.RemoveCollectionItemRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_collection_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_collection_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.RemoveCollectionItemResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.RemoveCollectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.remove_collection_item(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_collection_item_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_collection_item._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("item", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_collection_item_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_remove_collection_item") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_remove_collection_item") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.RemoveCollectionItemRequest.pb(warehouse.RemoveCollectionItemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.RemoveCollectionItemResponse.to_json(warehouse.RemoveCollectionItemResponse()) + + request = warehouse.RemoveCollectionItemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.RemoveCollectionItemResponse() + + client.remove_collection_item(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_collection_item_rest_bad_request(transport: str = 'rest', request_type=warehouse.RemoveCollectionItemRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'item': {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.remove_collection_item(request) + + +def test_remove_collection_item_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.RemoveCollectionItemResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'item': {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + item=warehouse.CollectionItem(collection='collection_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.RemoveCollectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.remove_collection_item(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{item.collection=projects/*/locations/*/corpora/*/collections/*}:removeCollectionItem" % client.transport._host, args[1]) + + +def test_remove_collection_item_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_collection_item( + warehouse.RemoveCollectionItemRequest(), + item=warehouse.CollectionItem(collection='collection_value'), + ) + + +def test_remove_collection_item_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ViewCollectionItemsRequest, + dict, +]) +def test_view_collection_items_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ViewCollectionItemsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ViewCollectionItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.view_collection_items(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ViewCollectionItemsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_view_collection_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.view_collection_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.view_collection_items] = mock_rpc + + request = {} + client.view_collection_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.view_collection_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_view_collection_items_rest_required_fields(request_type=warehouse.ViewCollectionItemsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["collection"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).view_collection_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["collection"] = 'collection_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).view_collection_items._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "collection" in jsonified_request + assert jsonified_request["collection"] == 'collection_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ViewCollectionItemsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ViewCollectionItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.view_collection_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_view_collection_items_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.view_collection_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("collection", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_view_collection_items_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_view_collection_items") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_view_collection_items") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ViewCollectionItemsRequest.pb(warehouse.ViewCollectionItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ViewCollectionItemsResponse.to_json(warehouse.ViewCollectionItemsResponse()) + + request = warehouse.ViewCollectionItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ViewCollectionItemsResponse() + + client.view_collection_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_view_collection_items_rest_bad_request(transport: str = 'rest', request_type=warehouse.ViewCollectionItemsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.view_collection_items(request) + + +def test_view_collection_items_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ViewCollectionItemsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + collection='collection_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ViewCollectionItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.view_collection_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{collection=projects/*/locations/*/corpora/*/collections/*}:viewCollectionItems" % client.transport._host, args[1]) + + +def test_view_collection_items_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.view_collection_items( + warehouse.ViewCollectionItemsRequest(), + collection='collection_value', + ) + + +def test_view_collection_items_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + next_page_token='abc', + ), + warehouse.ViewCollectionItemsResponse( + items=[], + next_page_token='def', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + ], + next_page_token='ghi', + ), + warehouse.ViewCollectionItemsResponse( + items=[ + warehouse.CollectionItem(), + warehouse.CollectionItem(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ViewCollectionItemsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'collection': 'projects/sample1/locations/sample2/corpora/sample3/collections/sample4'} + + pager = client.view_collection_items(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.CollectionItem) + for i in results) + + pages = list(client.view_collection_items(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_ingest_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.ingest_asset({}) + assert ( + "Method IngestAsset is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WarehouseClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WarehouseClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WarehouseClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WarehouseClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WarehouseClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WarehouseGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WarehouseGrpcTransport, + transports.WarehouseGrpcAsyncIOTransport, + transports.WarehouseRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = WarehouseClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WarehouseGrpcTransport, + ) + +def test_warehouse_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WarehouseTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_warehouse_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1.services.warehouse.transports.WarehouseTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WarehouseTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_asset', + 'update_asset', + 'get_asset', + 'list_assets', + 'delete_asset', + 'upload_asset', + 'generate_retrieval_url', + 'analyze_asset', + 'index_asset', + 'remove_index_asset', + 'view_indexed_assets', + 'create_index', + 'update_index', + 'get_index', + 'list_indexes', + 'delete_index', + 'create_corpus', + 'get_corpus', + 'update_corpus', + 'list_corpora', + 'delete_corpus', + 'analyze_corpus', + 'create_data_schema', + 'update_data_schema', + 'get_data_schema', + 'delete_data_schema', + 'list_data_schemas', + 'create_annotation', + 'get_annotation', + 'list_annotations', + 'update_annotation', + 'delete_annotation', + 'ingest_asset', + 'clip_asset', + 'generate_hls_uri', + 'import_assets', + 'create_search_config', + 'update_search_config', + 'get_search_config', + 'delete_search_config', + 'list_search_configs', + 'create_search_hypernym', + 'update_search_hypernym', + 'get_search_hypernym', + 'delete_search_hypernym', + 'list_search_hypernyms', + 'search_assets', + 'search_index_endpoint', + 'create_index_endpoint', + 'get_index_endpoint', + 'list_index_endpoints', + 'update_index_endpoint', + 'delete_index_endpoint', + 'deploy_index', + 'undeploy_index', + 'create_collection', + 'delete_collection', + 'get_collection', + 'update_collection', + 'list_collections', + 'add_collection_item', + 'remove_collection_item', + 'view_collection_items', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_warehouse_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1.services.warehouse.transports.WarehouseTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WarehouseTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_warehouse_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1.services.warehouse.transports.WarehouseTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WarehouseTransport() + adc.assert_called_once() + + +def test_warehouse_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) + WarehouseClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WarehouseGrpcTransport, + transports.WarehouseGrpcAsyncIOTransport, + ], +) +def test_warehouse_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WarehouseGrpcTransport, + transports.WarehouseGrpcAsyncIOTransport, + transports.WarehouseRestTransport, + ], +) +def test_warehouse_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WarehouseGrpcTransport, grpc_helpers), + (transports.WarehouseGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_warehouse_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( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WarehouseGrpcTransport, transports.WarehouseGrpcAsyncIOTransport]) +def test_warehouse_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_warehouse_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.WarehouseRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_warehouse_rest_lro_client(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_warehouse_host_no_port(transport_name): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_warehouse_host_with_port(transport_name): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_warehouse_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WarehouseClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WarehouseClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_asset._session + session2 = client2.transport.create_asset._session + assert session1 != session2 + session1 = client1.transport.update_asset._session + session2 = client2.transport.update_asset._session + assert session1 != session2 + session1 = client1.transport.get_asset._session + session2 = client2.transport.get_asset._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.delete_asset._session + session2 = client2.transport.delete_asset._session + assert session1 != session2 + session1 = client1.transport.upload_asset._session + session2 = client2.transport.upload_asset._session + assert session1 != session2 + session1 = client1.transport.generate_retrieval_url._session + session2 = client2.transport.generate_retrieval_url._session + assert session1 != session2 + session1 = client1.transport.analyze_asset._session + session2 = client2.transport.analyze_asset._session + assert session1 != session2 + session1 = client1.transport.index_asset._session + session2 = client2.transport.index_asset._session + assert session1 != session2 + session1 = client1.transport.remove_index_asset._session + session2 = client2.transport.remove_index_asset._session + assert session1 != session2 + session1 = client1.transport.view_indexed_assets._session + session2 = client2.transport.view_indexed_assets._session + assert session1 != session2 + session1 = client1.transport.create_index._session + session2 = client2.transport.create_index._session + assert session1 != session2 + session1 = client1.transport.update_index._session + session2 = client2.transport.update_index._session + assert session1 != session2 + session1 = client1.transport.get_index._session + session2 = client2.transport.get_index._session + assert session1 != session2 + session1 = client1.transport.list_indexes._session + session2 = client2.transport.list_indexes._session + assert session1 != session2 + session1 = client1.transport.delete_index._session + session2 = client2.transport.delete_index._session + assert session1 != session2 + session1 = client1.transport.create_corpus._session + session2 = client2.transport.create_corpus._session + assert session1 != session2 + session1 = client1.transport.get_corpus._session + session2 = client2.transport.get_corpus._session + assert session1 != session2 + session1 = client1.transport.update_corpus._session + session2 = client2.transport.update_corpus._session + assert session1 != session2 + session1 = client1.transport.list_corpora._session + session2 = client2.transport.list_corpora._session + assert session1 != session2 + session1 = client1.transport.delete_corpus._session + session2 = client2.transport.delete_corpus._session + assert session1 != session2 + session1 = client1.transport.analyze_corpus._session + session2 = client2.transport.analyze_corpus._session + assert session1 != session2 + session1 = client1.transport.create_data_schema._session + session2 = client2.transport.create_data_schema._session + assert session1 != session2 + session1 = client1.transport.update_data_schema._session + session2 = client2.transport.update_data_schema._session + assert session1 != session2 + session1 = client1.transport.get_data_schema._session + session2 = client2.transport.get_data_schema._session + assert session1 != session2 + session1 = client1.transport.delete_data_schema._session + session2 = client2.transport.delete_data_schema._session + assert session1 != session2 + session1 = client1.transport.list_data_schemas._session + session2 = client2.transport.list_data_schemas._session + assert session1 != session2 + session1 = client1.transport.create_annotation._session + session2 = client2.transport.create_annotation._session + assert session1 != session2 + session1 = client1.transport.get_annotation._session + session2 = client2.transport.get_annotation._session + assert session1 != session2 + session1 = client1.transport.list_annotations._session + session2 = client2.transport.list_annotations._session + assert session1 != session2 + session1 = client1.transport.update_annotation._session + session2 = client2.transport.update_annotation._session + assert session1 != session2 + session1 = client1.transport.delete_annotation._session + session2 = client2.transport.delete_annotation._session + assert session1 != session2 + session1 = client1.transport.ingest_asset._session + session2 = client2.transport.ingest_asset._session + assert session1 != session2 + session1 = client1.transport.clip_asset._session + session2 = client2.transport.clip_asset._session + assert session1 != session2 + session1 = client1.transport.generate_hls_uri._session + session2 = client2.transport.generate_hls_uri._session + assert session1 != session2 + session1 = client1.transport.import_assets._session + session2 = client2.transport.import_assets._session + assert session1 != session2 + session1 = client1.transport.create_search_config._session + session2 = client2.transport.create_search_config._session + assert session1 != session2 + session1 = client1.transport.update_search_config._session + session2 = client2.transport.update_search_config._session + assert session1 != session2 + session1 = client1.transport.get_search_config._session + session2 = client2.transport.get_search_config._session + assert session1 != session2 + session1 = client1.transport.delete_search_config._session + session2 = client2.transport.delete_search_config._session + assert session1 != session2 + session1 = client1.transport.list_search_configs._session + session2 = client2.transport.list_search_configs._session + assert session1 != session2 + session1 = client1.transport.create_search_hypernym._session + session2 = client2.transport.create_search_hypernym._session + assert session1 != session2 + session1 = client1.transport.update_search_hypernym._session + session2 = client2.transport.update_search_hypernym._session + assert session1 != session2 + session1 = client1.transport.get_search_hypernym._session + session2 = client2.transport.get_search_hypernym._session + assert session1 != session2 + session1 = client1.transport.delete_search_hypernym._session + session2 = client2.transport.delete_search_hypernym._session + assert session1 != session2 + session1 = client1.transport.list_search_hypernyms._session + session2 = client2.transport.list_search_hypernyms._session + assert session1 != session2 + session1 = client1.transport.search_assets._session + session2 = client2.transport.search_assets._session + assert session1 != session2 + session1 = client1.transport.search_index_endpoint._session + session2 = client2.transport.search_index_endpoint._session + assert session1 != session2 + session1 = client1.transport.create_index_endpoint._session + session2 = client2.transport.create_index_endpoint._session + assert session1 != session2 + session1 = client1.transport.get_index_endpoint._session + session2 = client2.transport.get_index_endpoint._session + assert session1 != session2 + session1 = client1.transport.list_index_endpoints._session + session2 = client2.transport.list_index_endpoints._session + assert session1 != session2 + session1 = client1.transport.update_index_endpoint._session + session2 = client2.transport.update_index_endpoint._session + assert session1 != session2 + session1 = client1.transport.delete_index_endpoint._session + session2 = client2.transport.delete_index_endpoint._session + assert session1 != session2 + session1 = client1.transport.deploy_index._session + session2 = client2.transport.deploy_index._session + assert session1 != session2 + session1 = client1.transport.undeploy_index._session + session2 = client2.transport.undeploy_index._session + assert session1 != session2 + session1 = client1.transport.create_collection._session + session2 = client2.transport.create_collection._session + assert session1 != session2 + session1 = client1.transport.delete_collection._session + session2 = client2.transport.delete_collection._session + assert session1 != session2 + session1 = client1.transport.get_collection._session + session2 = client2.transport.get_collection._session + assert session1 != session2 + session1 = client1.transport.update_collection._session + session2 = client2.transport.update_collection._session + assert session1 != session2 + session1 = client1.transport.list_collections._session + session2 = client2.transport.list_collections._session + assert session1 != session2 + session1 = client1.transport.add_collection_item._session + session2 = client2.transport.add_collection_item._session + assert session1 != session2 + session1 = client1.transport.remove_collection_item._session + session2 = client2.transport.remove_collection_item._session + assert session1 != session2 + session1 = client1.transport.view_collection_items._session + session2 = client2.transport.view_collection_items._session + assert session1 != session2 +def test_warehouse_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WarehouseGrpcTransport( + 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_warehouse_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WarehouseGrpcAsyncIOTransport( + 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.WarehouseGrpcTransport, transports.WarehouseGrpcAsyncIOTransport]) +def test_warehouse_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.WarehouseGrpcTransport, transports.WarehouseGrpcAsyncIOTransport]) +def test_warehouse_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_warehouse_grpc_lro_client(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_warehouse_grpc_lro_async_client(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_annotation_path(): + project_number = "squid" + location = "clam" + corpus = "whelk" + asset = "octopus" + annotation = "oyster" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, annotation=annotation, ) + actual = WarehouseClient.annotation_path(project_number, location, corpus, asset, annotation) + assert expected == actual + + +def test_parse_annotation_path(): + expected = { + "project_number": "nudibranch", + "location": "cuttlefish", + "corpus": "mussel", + "asset": "winkle", + "annotation": "nautilus", + } + path = WarehouseClient.annotation_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_annotation_path(path) + assert expected == actual + +def test_asset_path(): + project_number = "scallop" + location = "abalone" + corpus = "squid" + asset = "clam" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, ) + actual = WarehouseClient.asset_path(project_number, location, corpus, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "project_number": "whelk", + "location": "octopus", + "corpus": "oyster", + "asset": "nudibranch", + } + path = WarehouseClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_asset_path(path) + assert expected == actual + +def test_collection_path(): + project_number = "cuttlefish" + location = "mussel" + corpus = "winkle" + collection = "nautilus" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/collections/{collection}".format(project_number=project_number, location=location, corpus=corpus, collection=collection, ) + actual = WarehouseClient.collection_path(project_number, location, corpus, collection) + assert expected == actual + + +def test_parse_collection_path(): + expected = { + "project_number": "scallop", + "location": "abalone", + "corpus": "squid", + "collection": "clam", + } + path = WarehouseClient.collection_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_collection_path(path) + assert expected == actual + +def test_corpus_path(): + project_number = "whelk" + location = "octopus" + corpus = "oyster" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}".format(project_number=project_number, location=location, corpus=corpus, ) + actual = WarehouseClient.corpus_path(project_number, location, corpus) + assert expected == actual + + +def test_parse_corpus_path(): + expected = { + "project_number": "nudibranch", + "location": "cuttlefish", + "corpus": "mussel", + } + path = WarehouseClient.corpus_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_corpus_path(path) + assert expected == actual + +def test_data_schema_path(): + project_number = "winkle" + location = "nautilus" + corpus = "scallop" + data_schema = "abalone" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}".format(project_number=project_number, location=location, corpus=corpus, data_schema=data_schema, ) + actual = WarehouseClient.data_schema_path(project_number, location, corpus, data_schema) + assert expected == actual + + +def test_parse_data_schema_path(): + expected = { + "project_number": "squid", + "location": "clam", + "corpus": "whelk", + "data_schema": "octopus", + } + path = WarehouseClient.data_schema_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_data_schema_path(path) + assert expected == actual + +def test_index_path(): + project_number = "oyster" + location = "nudibranch" + corpus = "cuttlefish" + index = "mussel" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}".format(project_number=project_number, location=location, corpus=corpus, index=index, ) + actual = WarehouseClient.index_path(project_number, location, corpus, index) + assert expected == actual + + +def test_parse_index_path(): + expected = { + "project_number": "winkle", + "location": "nautilus", + "corpus": "scallop", + "index": "abalone", + } + path = WarehouseClient.index_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_index_path(path) + assert expected == actual + +def test_index_endpoint_path(): + project = "squid" + location = "clam" + index_endpoint = "whelk" + expected = "projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}".format(project=project, location=location, index_endpoint=index_endpoint, ) + actual = WarehouseClient.index_endpoint_path(project, location, index_endpoint) + assert expected == actual + + +def test_parse_index_endpoint_path(): + expected = { + "project": "octopus", + "location": "oyster", + "index_endpoint": "nudibranch", + } + path = WarehouseClient.index_endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_index_endpoint_path(path) + assert expected == actual + +def test_search_config_path(): + project_number = "cuttlefish" + location = "mussel" + corpus = "winkle" + search_config = "nautilus" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}".format(project_number=project_number, location=location, corpus=corpus, search_config=search_config, ) + actual = WarehouseClient.search_config_path(project_number, location, corpus, search_config) + assert expected == actual + + +def test_parse_search_config_path(): + expected = { + "project_number": "scallop", + "location": "abalone", + "corpus": "squid", + "search_config": "clam", + } + path = WarehouseClient.search_config_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_search_config_path(path) + assert expected == actual + +def test_search_hypernym_path(): + project_number = "whelk" + location = "octopus" + corpus = "oyster" + search_hypernym = "nudibranch" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/searchHypernyms/{search_hypernym}".format(project_number=project_number, location=location, corpus=corpus, search_hypernym=search_hypernym, ) + actual = WarehouseClient.search_hypernym_path(project_number, location, corpus, search_hypernym) + assert expected == actual + + +def test_parse_search_hypernym_path(): + expected = { + "project_number": "cuttlefish", + "location": "mussel", + "corpus": "winkle", + "search_hypernym": "nautilus", + } + path = WarehouseClient.search_hypernym_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_search_hypernym_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WarehouseClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = WarehouseClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = WarehouseClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = WarehouseClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WarehouseClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = WarehouseClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = WarehouseClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = WarehouseClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.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 = WarehouseClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = WarehouseClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.WarehouseTransport, '_prep_wrapped_messages') as prep: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WarehouseTransport, '_prep_wrapped_messages') as prep: + transport_class = WarehouseClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (WarehouseClient, transports.WarehouseGrpcTransport), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/.coveragerc b/owl-bot-staging/google-cloud-visionai/v1alpha1/.coveragerc new file mode 100644 index 000000000000..3fe38571c5ca --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/visionai/__init__.py + google/cloud/visionai/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/.flake8 b/owl-bot-staging/google-cloud-visionai/v1alpha1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/MANIFEST.in b/owl-bot-staging/google-cloud-visionai/v1alpha1/MANIFEST.in new file mode 100644 index 000000000000..a22f7c8f8452 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/visionai *.py +recursive-include google/cloud/visionai_v1alpha1 *.py diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/README.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/README.rst new file mode 100644 index 000000000000..eade452c535b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Visionai API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Visionai 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/google-cloud-visionai/v1alpha1/docs/_static/custom.css b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/conf.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/conf.py new file mode 100644 index 000000000000..2484432dcdae --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-visionai documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-visionai" +copyright = u"2023, 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 = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-visionai-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-visionai.tex", + u"google-cloud-visionai Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-visionai", + u"Google Cloud Visionai Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-visionai", + u"google-cloud-visionai Documentation", + author, + "google-cloud-visionai", + "GAPIC library for Google Cloud Visionai 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/google-cloud-visionai/v1alpha1/docs/index.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/index.rst new file mode 100644 index 000000000000..26880ba560b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + visionai_v1alpha1/services + visionai_v1alpha1/types diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/app_platform.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/app_platform.rst new file mode 100644 index 000000000000..9129534efc24 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/app_platform.rst @@ -0,0 +1,10 @@ +AppPlatform +----------------------------- + +.. automodule:: google.cloud.visionai_v1alpha1.services.app_platform + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1alpha1.services.app_platform.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/live_video_analytics.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/live_video_analytics.rst new file mode 100644 index 000000000000..d1a181429202 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/live_video_analytics.rst @@ -0,0 +1,10 @@ +LiveVideoAnalytics +------------------------------------ + +.. automodule:: google.cloud.visionai_v1alpha1.services.live_video_analytics + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1alpha1.services.live_video_analytics.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/services_.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/services_.rst new file mode 100644 index 000000000000..6dcdcd2924dd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/services_.rst @@ -0,0 +1,10 @@ +Services for Google Cloud Visionai v1alpha1 API +=============================================== +.. toctree:: + :maxdepth: 2 + + app_platform + live_video_analytics + streaming_service + streams_service + warehouse diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/streaming_service.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/streaming_service.rst new file mode 100644 index 000000000000..0e41f8896b1c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/streaming_service.rst @@ -0,0 +1,6 @@ +StreamingService +---------------------------------- + +.. automodule:: google.cloud.visionai_v1alpha1.services.streaming_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/streams_service.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/streams_service.rst new file mode 100644 index 000000000000..df2fc0fac6a7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/streams_service.rst @@ -0,0 +1,10 @@ +StreamsService +-------------------------------- + +.. automodule:: google.cloud.visionai_v1alpha1.services.streams_service + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1alpha1.services.streams_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/types_.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/types_.rst new file mode 100644 index 000000000000..12c1e074e208 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Visionai v1alpha1 API +============================================ + +.. automodule:: google.cloud.visionai_v1alpha1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/warehouse.rst b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/warehouse.rst new file mode 100644 index 000000000000..9a82ccb18f20 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/docs/visionai_v1alpha1/warehouse.rst @@ -0,0 +1,10 @@ +Warehouse +--------------------------- + +.. automodule:: google.cloud.visionai_v1alpha1.services.warehouse + :members: + :inherited-members: + +.. automodule:: google.cloud.visionai_v1alpha1.services.warehouse.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/__init__.py new file mode 100644 index 000000000000..bab600ae07c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/__init__.py @@ -0,0 +1,501 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.visionai import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.visionai_v1alpha1.services.app_platform.client import AppPlatformClient +from google.cloud.visionai_v1alpha1.services.app_platform.async_client import AppPlatformAsyncClient +from google.cloud.visionai_v1alpha1.services.live_video_analytics.client import LiveVideoAnalyticsClient +from google.cloud.visionai_v1alpha1.services.live_video_analytics.async_client import LiveVideoAnalyticsAsyncClient +from google.cloud.visionai_v1alpha1.services.streaming_service.client import StreamingServiceClient +from google.cloud.visionai_v1alpha1.services.streaming_service.async_client import StreamingServiceAsyncClient +from google.cloud.visionai_v1alpha1.services.streams_service.client import StreamsServiceClient +from google.cloud.visionai_v1alpha1.services.streams_service.async_client import StreamsServiceAsyncClient +from google.cloud.visionai_v1alpha1.services.warehouse.client import WarehouseClient +from google.cloud.visionai_v1alpha1.services.warehouse.async_client import WarehouseAsyncClient + +from google.cloud.visionai_v1alpha1.types.annotations import AppPlatformCloudFunctionRequest +from google.cloud.visionai_v1alpha1.types.annotations import AppPlatformCloudFunctionResponse +from google.cloud.visionai_v1alpha1.types.annotations import AppPlatformEventBody +from google.cloud.visionai_v1alpha1.types.annotations import AppPlatformMetadata +from google.cloud.visionai_v1alpha1.types.annotations import ClassificationPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import ImageObjectDetectionPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import ImageSegmentationPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import NormalizedPolygon +from google.cloud.visionai_v1alpha1.types.annotations import NormalizedPolyline +from google.cloud.visionai_v1alpha1.types.annotations import NormalizedVertex +from google.cloud.visionai_v1alpha1.types.annotations import ObjectDetectionPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import OccupancyCountingPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import PersonalProtectiveEquipmentDetectionOutput +from google.cloud.visionai_v1alpha1.types.annotations import StreamAnnotation +from google.cloud.visionai_v1alpha1.types.annotations import StreamAnnotations +from google.cloud.visionai_v1alpha1.types.annotations import VideoActionRecognitionPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import VideoClassificationPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import VideoObjectTrackingPredictionResult +from google.cloud.visionai_v1alpha1.types.annotations import StreamAnnotationType +from google.cloud.visionai_v1alpha1.types.common import Cluster +from google.cloud.visionai_v1alpha1.types.common import GcsSource +from google.cloud.visionai_v1alpha1.types.common import OperationMetadata +from google.cloud.visionai_v1alpha1.types.lva import AnalysisDefinition +from google.cloud.visionai_v1alpha1.types.lva import AnalyzerDefinition +from google.cloud.visionai_v1alpha1.types.lva import AttributeValue +from google.cloud.visionai_v1alpha1.types.lva_resources import Analysis +from google.cloud.visionai_v1alpha1.types.lva_service import CreateAnalysisRequest +from google.cloud.visionai_v1alpha1.types.lva_service import DeleteAnalysisRequest +from google.cloud.visionai_v1alpha1.types.lva_service import GetAnalysisRequest +from google.cloud.visionai_v1alpha1.types.lva_service import ListAnalysesRequest +from google.cloud.visionai_v1alpha1.types.lva_service import ListAnalysesResponse +from google.cloud.visionai_v1alpha1.types.lva_service import UpdateAnalysisRequest +from google.cloud.visionai_v1alpha1.types.platform import AddApplicationStreamInputRequest +from google.cloud.visionai_v1alpha1.types.platform import AddApplicationStreamInputResponse +from google.cloud.visionai_v1alpha1.types.platform import AIEnabledDevicesInputConfig +from google.cloud.visionai_v1alpha1.types.platform import Application +from google.cloud.visionai_v1alpha1.types.platform import ApplicationConfigs +from google.cloud.visionai_v1alpha1.types.platform import ApplicationInstance +from google.cloud.visionai_v1alpha1.types.platform import ApplicationNodeAnnotation +from google.cloud.visionai_v1alpha1.types.platform import ApplicationStreamInput +from google.cloud.visionai_v1alpha1.types.platform import AutoscalingMetricSpec +from google.cloud.visionai_v1alpha1.types.platform import BigQueryConfig +from google.cloud.visionai_v1alpha1.types.platform import CreateApplicationInstancesRequest +from google.cloud.visionai_v1alpha1.types.platform import CreateApplicationInstancesResponse +from google.cloud.visionai_v1alpha1.types.platform import CreateApplicationRequest +from google.cloud.visionai_v1alpha1.types.platform import CreateDraftRequest +from google.cloud.visionai_v1alpha1.types.platform import CreateProcessorRequest +from google.cloud.visionai_v1alpha1.types.platform import CustomProcessorSourceInfo +from google.cloud.visionai_v1alpha1.types.platform import DedicatedResources +from google.cloud.visionai_v1alpha1.types.platform import DeleteApplicationInstancesRequest +from google.cloud.visionai_v1alpha1.types.platform import DeleteApplicationInstancesResponse +from google.cloud.visionai_v1alpha1.types.platform import DeleteApplicationRequest +from google.cloud.visionai_v1alpha1.types.platform import DeleteDraftRequest +from google.cloud.visionai_v1alpha1.types.platform import DeleteProcessorRequest +from google.cloud.visionai_v1alpha1.types.platform import DeployApplicationRequest +from google.cloud.visionai_v1alpha1.types.platform import DeployApplicationResponse +from google.cloud.visionai_v1alpha1.types.platform import Draft +from google.cloud.visionai_v1alpha1.types.platform import GeneralObjectDetectionConfig +from google.cloud.visionai_v1alpha1.types.platform import GetApplicationRequest +from google.cloud.visionai_v1alpha1.types.platform import GetDraftRequest +from google.cloud.visionai_v1alpha1.types.platform import GetInstanceRequest +from google.cloud.visionai_v1alpha1.types.platform import GetProcessorRequest +from google.cloud.visionai_v1alpha1.types.platform import Instance +from google.cloud.visionai_v1alpha1.types.platform import ListApplicationsRequest +from google.cloud.visionai_v1alpha1.types.platform import ListApplicationsResponse +from google.cloud.visionai_v1alpha1.types.platform import ListDraftsRequest +from google.cloud.visionai_v1alpha1.types.platform import ListDraftsResponse +from google.cloud.visionai_v1alpha1.types.platform import ListInstancesRequest +from google.cloud.visionai_v1alpha1.types.platform import ListInstancesResponse +from google.cloud.visionai_v1alpha1.types.platform import ListPrebuiltProcessorsRequest +from google.cloud.visionai_v1alpha1.types.platform import ListPrebuiltProcessorsResponse +from google.cloud.visionai_v1alpha1.types.platform import ListProcessorsRequest +from google.cloud.visionai_v1alpha1.types.platform import ListProcessorsResponse +from google.cloud.visionai_v1alpha1.types.platform import MachineSpec +from google.cloud.visionai_v1alpha1.types.platform import MediaWarehouseConfig +from google.cloud.visionai_v1alpha1.types.platform import Node +from google.cloud.visionai_v1alpha1.types.platform import OccupancyCountConfig +from google.cloud.visionai_v1alpha1.types.platform import PersonalProtectiveEquipmentDetectionConfig +from google.cloud.visionai_v1alpha1.types.platform import PersonBlurConfig +from google.cloud.visionai_v1alpha1.types.platform import PersonVehicleDetectionConfig +from google.cloud.visionai_v1alpha1.types.platform import Processor +from google.cloud.visionai_v1alpha1.types.platform import ProcessorConfig +from google.cloud.visionai_v1alpha1.types.platform import ProcessorIOSpec +from google.cloud.visionai_v1alpha1.types.platform import RemoveApplicationStreamInputRequest +from google.cloud.visionai_v1alpha1.types.platform import RemoveApplicationStreamInputResponse +from google.cloud.visionai_v1alpha1.types.platform import ResourceAnnotations +from google.cloud.visionai_v1alpha1.types.platform import StreamWithAnnotation +from google.cloud.visionai_v1alpha1.types.platform import UndeployApplicationRequest +from google.cloud.visionai_v1alpha1.types.platform import UndeployApplicationResponse +from google.cloud.visionai_v1alpha1.types.platform import UpdateApplicationInstancesRequest +from google.cloud.visionai_v1alpha1.types.platform import UpdateApplicationInstancesResponse +from google.cloud.visionai_v1alpha1.types.platform import UpdateApplicationRequest +from google.cloud.visionai_v1alpha1.types.platform import UpdateApplicationStreamInputRequest +from google.cloud.visionai_v1alpha1.types.platform import UpdateApplicationStreamInputResponse +from google.cloud.visionai_v1alpha1.types.platform import UpdateDraftRequest +from google.cloud.visionai_v1alpha1.types.platform import UpdateProcessorRequest +from google.cloud.visionai_v1alpha1.types.platform import VertexAutoMLVideoConfig +from google.cloud.visionai_v1alpha1.types.platform import VertexAutoMLVisionConfig +from google.cloud.visionai_v1alpha1.types.platform import VertexCustomConfig +from google.cloud.visionai_v1alpha1.types.platform import VideoStreamInputConfig +from google.cloud.visionai_v1alpha1.types.platform import AcceleratorType +from google.cloud.visionai_v1alpha1.types.platform import ModelType +from google.cloud.visionai_v1alpha1.types.streaming_resources import GstreamerBufferDescriptor +from google.cloud.visionai_v1alpha1.types.streaming_resources import Packet +from google.cloud.visionai_v1alpha1.types.streaming_resources import PacketHeader +from google.cloud.visionai_v1alpha1.types.streaming_resources import PacketType +from google.cloud.visionai_v1alpha1.types.streaming_resources import RawImageDescriptor +from google.cloud.visionai_v1alpha1.types.streaming_resources import SeriesMetadata +from google.cloud.visionai_v1alpha1.types.streaming_resources import ServerMetadata +from google.cloud.visionai_v1alpha1.types.streaming_service import AcquireLeaseRequest +from google.cloud.visionai_v1alpha1.types.streaming_service import CommitRequest +from google.cloud.visionai_v1alpha1.types.streaming_service import ControlledMode +from google.cloud.visionai_v1alpha1.types.streaming_service import EagerMode +from google.cloud.visionai_v1alpha1.types.streaming_service import EventUpdate +from google.cloud.visionai_v1alpha1.types.streaming_service import Lease +from google.cloud.visionai_v1alpha1.types.streaming_service import ReceiveEventsControlResponse +from google.cloud.visionai_v1alpha1.types.streaming_service import ReceiveEventsRequest +from google.cloud.visionai_v1alpha1.types.streaming_service import ReceiveEventsResponse +from google.cloud.visionai_v1alpha1.types.streaming_service import ReceivePacketsControlResponse +from google.cloud.visionai_v1alpha1.types.streaming_service import ReceivePacketsRequest +from google.cloud.visionai_v1alpha1.types.streaming_service import ReceivePacketsResponse +from google.cloud.visionai_v1alpha1.types.streaming_service import ReleaseLeaseRequest +from google.cloud.visionai_v1alpha1.types.streaming_service import ReleaseLeaseResponse +from google.cloud.visionai_v1alpha1.types.streaming_service import RenewLeaseRequest +from google.cloud.visionai_v1alpha1.types.streaming_service import RequestMetadata +from google.cloud.visionai_v1alpha1.types.streaming_service import SendPacketsRequest +from google.cloud.visionai_v1alpha1.types.streaming_service import SendPacketsResponse +from google.cloud.visionai_v1alpha1.types.streaming_service import LeaseType +from google.cloud.visionai_v1alpha1.types.streams_resources import Channel +from google.cloud.visionai_v1alpha1.types.streams_resources import Event +from google.cloud.visionai_v1alpha1.types.streams_resources import Series +from google.cloud.visionai_v1alpha1.types.streams_resources import Stream +from google.cloud.visionai_v1alpha1.types.streams_service import CreateClusterRequest +from google.cloud.visionai_v1alpha1.types.streams_service import CreateEventRequest +from google.cloud.visionai_v1alpha1.types.streams_service import CreateSeriesRequest +from google.cloud.visionai_v1alpha1.types.streams_service import CreateStreamRequest +from google.cloud.visionai_v1alpha1.types.streams_service import DeleteClusterRequest +from google.cloud.visionai_v1alpha1.types.streams_service import DeleteEventRequest +from google.cloud.visionai_v1alpha1.types.streams_service import DeleteSeriesRequest +from google.cloud.visionai_v1alpha1.types.streams_service import DeleteStreamRequest +from google.cloud.visionai_v1alpha1.types.streams_service import GenerateStreamHlsTokenRequest +from google.cloud.visionai_v1alpha1.types.streams_service import GenerateStreamHlsTokenResponse +from google.cloud.visionai_v1alpha1.types.streams_service import GetClusterRequest +from google.cloud.visionai_v1alpha1.types.streams_service import GetEventRequest +from google.cloud.visionai_v1alpha1.types.streams_service import GetSeriesRequest +from google.cloud.visionai_v1alpha1.types.streams_service import GetStreamRequest +from google.cloud.visionai_v1alpha1.types.streams_service import GetStreamThumbnailResponse +from google.cloud.visionai_v1alpha1.types.streams_service import ListClustersRequest +from google.cloud.visionai_v1alpha1.types.streams_service import ListClustersResponse +from google.cloud.visionai_v1alpha1.types.streams_service import ListEventsRequest +from google.cloud.visionai_v1alpha1.types.streams_service import ListEventsResponse +from google.cloud.visionai_v1alpha1.types.streams_service import ListSeriesRequest +from google.cloud.visionai_v1alpha1.types.streams_service import ListSeriesResponse +from google.cloud.visionai_v1alpha1.types.streams_service import ListStreamsRequest +from google.cloud.visionai_v1alpha1.types.streams_service import ListStreamsResponse +from google.cloud.visionai_v1alpha1.types.streams_service import MaterializeChannelRequest +from google.cloud.visionai_v1alpha1.types.streams_service import UpdateClusterRequest +from google.cloud.visionai_v1alpha1.types.streams_service import UpdateEventRequest +from google.cloud.visionai_v1alpha1.types.streams_service import UpdateSeriesRequest +from google.cloud.visionai_v1alpha1.types.streams_service import UpdateStreamRequest +from google.cloud.visionai_v1alpha1.types.warehouse import Annotation +from google.cloud.visionai_v1alpha1.types.warehouse import AnnotationMatchingResult +from google.cloud.visionai_v1alpha1.types.warehouse import AnnotationValue +from google.cloud.visionai_v1alpha1.types.warehouse import Asset +from google.cloud.visionai_v1alpha1.types.warehouse import BoolValue +from google.cloud.visionai_v1alpha1.types.warehouse import CircleArea +from google.cloud.visionai_v1alpha1.types.warehouse import ClipAssetRequest +from google.cloud.visionai_v1alpha1.types.warehouse import ClipAssetResponse +from google.cloud.visionai_v1alpha1.types.warehouse import Corpus +from google.cloud.visionai_v1alpha1.types.warehouse import CreateAnnotationRequest +from google.cloud.visionai_v1alpha1.types.warehouse import CreateAssetRequest +from google.cloud.visionai_v1alpha1.types.warehouse import CreateCorpusMetadata +from google.cloud.visionai_v1alpha1.types.warehouse import CreateCorpusRequest +from google.cloud.visionai_v1alpha1.types.warehouse import CreateDataSchemaRequest +from google.cloud.visionai_v1alpha1.types.warehouse import CreateSearchConfigRequest +from google.cloud.visionai_v1alpha1.types.warehouse import Criteria +from google.cloud.visionai_v1alpha1.types.warehouse import DataSchema +from google.cloud.visionai_v1alpha1.types.warehouse import DataSchemaDetails +from google.cloud.visionai_v1alpha1.types.warehouse import DateTimeRange +from google.cloud.visionai_v1alpha1.types.warehouse import DateTimeRangeArray +from google.cloud.visionai_v1alpha1.types.warehouse import DeleteAnnotationRequest +from google.cloud.visionai_v1alpha1.types.warehouse import DeleteAssetMetadata +from google.cloud.visionai_v1alpha1.types.warehouse import DeleteAssetRequest +from google.cloud.visionai_v1alpha1.types.warehouse import DeleteCorpusRequest +from google.cloud.visionai_v1alpha1.types.warehouse import DeleteDataSchemaRequest +from google.cloud.visionai_v1alpha1.types.warehouse import DeleteSearchConfigRequest +from google.cloud.visionai_v1alpha1.types.warehouse import FacetBucket +from google.cloud.visionai_v1alpha1.types.warehouse import FacetGroup +from google.cloud.visionai_v1alpha1.types.warehouse import FacetProperty +from google.cloud.visionai_v1alpha1.types.warehouse import FacetValue +from google.cloud.visionai_v1alpha1.types.warehouse import FloatRange +from google.cloud.visionai_v1alpha1.types.warehouse import FloatRangeArray +from google.cloud.visionai_v1alpha1.types.warehouse import GenerateHlsUriRequest +from google.cloud.visionai_v1alpha1.types.warehouse import GenerateHlsUriResponse +from google.cloud.visionai_v1alpha1.types.warehouse import GeoCoordinate +from google.cloud.visionai_v1alpha1.types.warehouse import GeoLocationArray +from google.cloud.visionai_v1alpha1.types.warehouse import GetAnnotationRequest +from google.cloud.visionai_v1alpha1.types.warehouse import GetAssetRequest +from google.cloud.visionai_v1alpha1.types.warehouse import GetCorpusRequest +from google.cloud.visionai_v1alpha1.types.warehouse import GetDataSchemaRequest +from google.cloud.visionai_v1alpha1.types.warehouse import GetSearchConfigRequest +from google.cloud.visionai_v1alpha1.types.warehouse import IngestAssetRequest +from google.cloud.visionai_v1alpha1.types.warehouse import IngestAssetResponse +from google.cloud.visionai_v1alpha1.types.warehouse import IntRange +from google.cloud.visionai_v1alpha1.types.warehouse import IntRangeArray +from google.cloud.visionai_v1alpha1.types.warehouse import ListAnnotationsRequest +from google.cloud.visionai_v1alpha1.types.warehouse import ListAnnotationsResponse +from google.cloud.visionai_v1alpha1.types.warehouse import ListAssetsRequest +from google.cloud.visionai_v1alpha1.types.warehouse import ListAssetsResponse +from google.cloud.visionai_v1alpha1.types.warehouse import ListCorporaRequest +from google.cloud.visionai_v1alpha1.types.warehouse import ListCorporaResponse +from google.cloud.visionai_v1alpha1.types.warehouse import ListDataSchemasRequest +from google.cloud.visionai_v1alpha1.types.warehouse import ListDataSchemasResponse +from google.cloud.visionai_v1alpha1.types.warehouse import ListSearchConfigsRequest +from google.cloud.visionai_v1alpha1.types.warehouse import ListSearchConfigsResponse +from google.cloud.visionai_v1alpha1.types.warehouse import Partition +from google.cloud.visionai_v1alpha1.types.warehouse import SearchAssetsRequest +from google.cloud.visionai_v1alpha1.types.warehouse import SearchAssetsResponse +from google.cloud.visionai_v1alpha1.types.warehouse import SearchConfig +from google.cloud.visionai_v1alpha1.types.warehouse import SearchCriteriaProperty +from google.cloud.visionai_v1alpha1.types.warehouse import SearchResultItem +from google.cloud.visionai_v1alpha1.types.warehouse import StringArray +from google.cloud.visionai_v1alpha1.types.warehouse import UpdateAnnotationRequest +from google.cloud.visionai_v1alpha1.types.warehouse import UpdateAssetRequest +from google.cloud.visionai_v1alpha1.types.warehouse import UpdateCorpusRequest +from google.cloud.visionai_v1alpha1.types.warehouse import UpdateDataSchemaRequest +from google.cloud.visionai_v1alpha1.types.warehouse import UpdateSearchConfigRequest +from google.cloud.visionai_v1alpha1.types.warehouse import UserSpecifiedAnnotation +from google.cloud.visionai_v1alpha1.types.warehouse import FacetBucketType + +__all__ = ('AppPlatformClient', + 'AppPlatformAsyncClient', + 'LiveVideoAnalyticsClient', + 'LiveVideoAnalyticsAsyncClient', + 'StreamingServiceClient', + 'StreamingServiceAsyncClient', + 'StreamsServiceClient', + 'StreamsServiceAsyncClient', + 'WarehouseClient', + 'WarehouseAsyncClient', + 'AppPlatformCloudFunctionRequest', + 'AppPlatformCloudFunctionResponse', + 'AppPlatformEventBody', + 'AppPlatformMetadata', + 'ClassificationPredictionResult', + 'ImageObjectDetectionPredictionResult', + 'ImageSegmentationPredictionResult', + 'NormalizedPolygon', + 'NormalizedPolyline', + 'NormalizedVertex', + 'ObjectDetectionPredictionResult', + 'OccupancyCountingPredictionResult', + 'PersonalProtectiveEquipmentDetectionOutput', + 'StreamAnnotation', + 'StreamAnnotations', + 'VideoActionRecognitionPredictionResult', + 'VideoClassificationPredictionResult', + 'VideoObjectTrackingPredictionResult', + 'StreamAnnotationType', + 'Cluster', + 'GcsSource', + 'OperationMetadata', + 'AnalysisDefinition', + 'AnalyzerDefinition', + 'AttributeValue', + 'Analysis', + 'CreateAnalysisRequest', + 'DeleteAnalysisRequest', + 'GetAnalysisRequest', + 'ListAnalysesRequest', + 'ListAnalysesResponse', + 'UpdateAnalysisRequest', + 'AddApplicationStreamInputRequest', + 'AddApplicationStreamInputResponse', + 'AIEnabledDevicesInputConfig', + 'Application', + 'ApplicationConfigs', + 'ApplicationInstance', + 'ApplicationNodeAnnotation', + 'ApplicationStreamInput', + 'AutoscalingMetricSpec', + 'BigQueryConfig', + 'CreateApplicationInstancesRequest', + 'CreateApplicationInstancesResponse', + 'CreateApplicationRequest', + 'CreateDraftRequest', + 'CreateProcessorRequest', + 'CustomProcessorSourceInfo', + 'DedicatedResources', + 'DeleteApplicationInstancesRequest', + 'DeleteApplicationInstancesResponse', + 'DeleteApplicationRequest', + 'DeleteDraftRequest', + 'DeleteProcessorRequest', + 'DeployApplicationRequest', + 'DeployApplicationResponse', + 'Draft', + 'GeneralObjectDetectionConfig', + 'GetApplicationRequest', + 'GetDraftRequest', + 'GetInstanceRequest', + 'GetProcessorRequest', + 'Instance', + 'ListApplicationsRequest', + 'ListApplicationsResponse', + 'ListDraftsRequest', + 'ListDraftsResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListPrebuiltProcessorsRequest', + 'ListPrebuiltProcessorsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'MachineSpec', + 'MediaWarehouseConfig', + 'Node', + 'OccupancyCountConfig', + 'PersonalProtectiveEquipmentDetectionConfig', + 'PersonBlurConfig', + 'PersonVehicleDetectionConfig', + 'Processor', + 'ProcessorConfig', + 'ProcessorIOSpec', + 'RemoveApplicationStreamInputRequest', + 'RemoveApplicationStreamInputResponse', + 'ResourceAnnotations', + 'StreamWithAnnotation', + 'UndeployApplicationRequest', + 'UndeployApplicationResponse', + 'UpdateApplicationInstancesRequest', + 'UpdateApplicationInstancesResponse', + 'UpdateApplicationRequest', + 'UpdateApplicationStreamInputRequest', + 'UpdateApplicationStreamInputResponse', + 'UpdateDraftRequest', + 'UpdateProcessorRequest', + 'VertexAutoMLVideoConfig', + 'VertexAutoMLVisionConfig', + 'VertexCustomConfig', + 'VideoStreamInputConfig', + 'AcceleratorType', + 'ModelType', + 'GstreamerBufferDescriptor', + 'Packet', + 'PacketHeader', + 'PacketType', + 'RawImageDescriptor', + 'SeriesMetadata', + 'ServerMetadata', + 'AcquireLeaseRequest', + 'CommitRequest', + 'ControlledMode', + 'EagerMode', + 'EventUpdate', + 'Lease', + 'ReceiveEventsControlResponse', + 'ReceiveEventsRequest', + 'ReceiveEventsResponse', + 'ReceivePacketsControlResponse', + 'ReceivePacketsRequest', + 'ReceivePacketsResponse', + 'ReleaseLeaseRequest', + 'ReleaseLeaseResponse', + 'RenewLeaseRequest', + 'RequestMetadata', + 'SendPacketsRequest', + 'SendPacketsResponse', + 'LeaseType', + 'Channel', + 'Event', + 'Series', + 'Stream', + 'CreateClusterRequest', + 'CreateEventRequest', + 'CreateSeriesRequest', + 'CreateStreamRequest', + 'DeleteClusterRequest', + 'DeleteEventRequest', + 'DeleteSeriesRequest', + 'DeleteStreamRequest', + 'GenerateStreamHlsTokenRequest', + 'GenerateStreamHlsTokenResponse', + 'GetClusterRequest', + 'GetEventRequest', + 'GetSeriesRequest', + 'GetStreamRequest', + 'GetStreamThumbnailResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListEventsRequest', + 'ListEventsResponse', + 'ListSeriesRequest', + 'ListSeriesResponse', + 'ListStreamsRequest', + 'ListStreamsResponse', + 'MaterializeChannelRequest', + 'UpdateClusterRequest', + 'UpdateEventRequest', + 'UpdateSeriesRequest', + 'UpdateStreamRequest', + 'Annotation', + 'AnnotationMatchingResult', + 'AnnotationValue', + 'Asset', + 'BoolValue', + 'CircleArea', + 'ClipAssetRequest', + 'ClipAssetResponse', + 'Corpus', + 'CreateAnnotationRequest', + 'CreateAssetRequest', + 'CreateCorpusMetadata', + 'CreateCorpusRequest', + 'CreateDataSchemaRequest', + 'CreateSearchConfigRequest', + 'Criteria', + 'DataSchema', + 'DataSchemaDetails', + 'DateTimeRange', + 'DateTimeRangeArray', + 'DeleteAnnotationRequest', + 'DeleteAssetMetadata', + 'DeleteAssetRequest', + 'DeleteCorpusRequest', + 'DeleteDataSchemaRequest', + 'DeleteSearchConfigRequest', + 'FacetBucket', + 'FacetGroup', + 'FacetProperty', + 'FacetValue', + 'FloatRange', + 'FloatRangeArray', + 'GenerateHlsUriRequest', + 'GenerateHlsUriResponse', + 'GeoCoordinate', + 'GeoLocationArray', + 'GetAnnotationRequest', + 'GetAssetRequest', + 'GetCorpusRequest', + 'GetDataSchemaRequest', + 'GetSearchConfigRequest', + 'IngestAssetRequest', + 'IngestAssetResponse', + 'IntRange', + 'IntRangeArray', + 'ListAnnotationsRequest', + 'ListAnnotationsResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListCorporaRequest', + 'ListCorporaResponse', + 'ListDataSchemasRequest', + 'ListDataSchemasResponse', + 'ListSearchConfigsRequest', + 'ListSearchConfigsResponse', + 'Partition', + 'SearchAssetsRequest', + 'SearchAssetsResponse', + 'SearchConfig', + 'SearchCriteriaProperty', + 'SearchResultItem', + 'StringArray', + 'UpdateAnnotationRequest', + 'UpdateAssetRequest', + 'UpdateCorpusRequest', + 'UpdateDataSchemaRequest', + 'UpdateSearchConfigRequest', + 'UserSpecifiedAnnotation', + 'FacetBucketType', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/gapic_version.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/py.typed b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/py.typed new file mode 100644 index 000000000000..7b2e82d731c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-visionai package uses inline types. diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/__init__.py new file mode 100644 index 000000000000..b03d2b443def --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/__init__.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.app_platform import AppPlatformClient +from .services.app_platform import AppPlatformAsyncClient +from .services.live_video_analytics import LiveVideoAnalyticsClient +from .services.live_video_analytics import LiveVideoAnalyticsAsyncClient +from .services.streaming_service import StreamingServiceClient +from .services.streaming_service import StreamingServiceAsyncClient +from .services.streams_service import StreamsServiceClient +from .services.streams_service import StreamsServiceAsyncClient +from .services.warehouse import WarehouseClient +from .services.warehouse import WarehouseAsyncClient + +from .types.annotations import AppPlatformCloudFunctionRequest +from .types.annotations import AppPlatformCloudFunctionResponse +from .types.annotations import AppPlatformEventBody +from .types.annotations import AppPlatformMetadata +from .types.annotations import ClassificationPredictionResult +from .types.annotations import ImageObjectDetectionPredictionResult +from .types.annotations import ImageSegmentationPredictionResult +from .types.annotations import NormalizedPolygon +from .types.annotations import NormalizedPolyline +from .types.annotations import NormalizedVertex +from .types.annotations import ObjectDetectionPredictionResult +from .types.annotations import OccupancyCountingPredictionResult +from .types.annotations import PersonalProtectiveEquipmentDetectionOutput +from .types.annotations import StreamAnnotation +from .types.annotations import StreamAnnotations +from .types.annotations import VideoActionRecognitionPredictionResult +from .types.annotations import VideoClassificationPredictionResult +from .types.annotations import VideoObjectTrackingPredictionResult +from .types.annotations import StreamAnnotationType +from .types.common import Cluster +from .types.common import GcsSource +from .types.common import OperationMetadata +from .types.lva import AnalysisDefinition +from .types.lva import AnalyzerDefinition +from .types.lva import AttributeValue +from .types.lva_resources import Analysis +from .types.lva_service import CreateAnalysisRequest +from .types.lva_service import DeleteAnalysisRequest +from .types.lva_service import GetAnalysisRequest +from .types.lva_service import ListAnalysesRequest +from .types.lva_service import ListAnalysesResponse +from .types.lva_service import UpdateAnalysisRequest +from .types.platform import AddApplicationStreamInputRequest +from .types.platform import AddApplicationStreamInputResponse +from .types.platform import AIEnabledDevicesInputConfig +from .types.platform import Application +from .types.platform import ApplicationConfigs +from .types.platform import ApplicationInstance +from .types.platform import ApplicationNodeAnnotation +from .types.platform import ApplicationStreamInput +from .types.platform import AutoscalingMetricSpec +from .types.platform import BigQueryConfig +from .types.platform import CreateApplicationInstancesRequest +from .types.platform import CreateApplicationInstancesResponse +from .types.platform import CreateApplicationRequest +from .types.platform import CreateDraftRequest +from .types.platform import CreateProcessorRequest +from .types.platform import CustomProcessorSourceInfo +from .types.platform import DedicatedResources +from .types.platform import DeleteApplicationInstancesRequest +from .types.platform import DeleteApplicationInstancesResponse +from .types.platform import DeleteApplicationRequest +from .types.platform import DeleteDraftRequest +from .types.platform import DeleteProcessorRequest +from .types.platform import DeployApplicationRequest +from .types.platform import DeployApplicationResponse +from .types.platform import Draft +from .types.platform import GeneralObjectDetectionConfig +from .types.platform import GetApplicationRequest +from .types.platform import GetDraftRequest +from .types.platform import GetInstanceRequest +from .types.platform import GetProcessorRequest +from .types.platform import Instance +from .types.platform import ListApplicationsRequest +from .types.platform import ListApplicationsResponse +from .types.platform import ListDraftsRequest +from .types.platform import ListDraftsResponse +from .types.platform import ListInstancesRequest +from .types.platform import ListInstancesResponse +from .types.platform import ListPrebuiltProcessorsRequest +from .types.platform import ListPrebuiltProcessorsResponse +from .types.platform import ListProcessorsRequest +from .types.platform import ListProcessorsResponse +from .types.platform import MachineSpec +from .types.platform import MediaWarehouseConfig +from .types.platform import Node +from .types.platform import OccupancyCountConfig +from .types.platform import PersonalProtectiveEquipmentDetectionConfig +from .types.platform import PersonBlurConfig +from .types.platform import PersonVehicleDetectionConfig +from .types.platform import Processor +from .types.platform import ProcessorConfig +from .types.platform import ProcessorIOSpec +from .types.platform import RemoveApplicationStreamInputRequest +from .types.platform import RemoveApplicationStreamInputResponse +from .types.platform import ResourceAnnotations +from .types.platform import StreamWithAnnotation +from .types.platform import UndeployApplicationRequest +from .types.platform import UndeployApplicationResponse +from .types.platform import UpdateApplicationInstancesRequest +from .types.platform import UpdateApplicationInstancesResponse +from .types.platform import UpdateApplicationRequest +from .types.platform import UpdateApplicationStreamInputRequest +from .types.platform import UpdateApplicationStreamInputResponse +from .types.platform import UpdateDraftRequest +from .types.platform import UpdateProcessorRequest +from .types.platform import VertexAutoMLVideoConfig +from .types.platform import VertexAutoMLVisionConfig +from .types.platform import VertexCustomConfig +from .types.platform import VideoStreamInputConfig +from .types.platform import AcceleratorType +from .types.platform import ModelType +from .types.streaming_resources import GstreamerBufferDescriptor +from .types.streaming_resources import Packet +from .types.streaming_resources import PacketHeader +from .types.streaming_resources import PacketType +from .types.streaming_resources import RawImageDescriptor +from .types.streaming_resources import SeriesMetadata +from .types.streaming_resources import ServerMetadata +from .types.streaming_service import AcquireLeaseRequest +from .types.streaming_service import CommitRequest +from .types.streaming_service import ControlledMode +from .types.streaming_service import EagerMode +from .types.streaming_service import EventUpdate +from .types.streaming_service import Lease +from .types.streaming_service import ReceiveEventsControlResponse +from .types.streaming_service import ReceiveEventsRequest +from .types.streaming_service import ReceiveEventsResponse +from .types.streaming_service import ReceivePacketsControlResponse +from .types.streaming_service import ReceivePacketsRequest +from .types.streaming_service import ReceivePacketsResponse +from .types.streaming_service import ReleaseLeaseRequest +from .types.streaming_service import ReleaseLeaseResponse +from .types.streaming_service import RenewLeaseRequest +from .types.streaming_service import RequestMetadata +from .types.streaming_service import SendPacketsRequest +from .types.streaming_service import SendPacketsResponse +from .types.streaming_service import LeaseType +from .types.streams_resources import Channel +from .types.streams_resources import Event +from .types.streams_resources import Series +from .types.streams_resources import Stream +from .types.streams_service import CreateClusterRequest +from .types.streams_service import CreateEventRequest +from .types.streams_service import CreateSeriesRequest +from .types.streams_service import CreateStreamRequest +from .types.streams_service import DeleteClusterRequest +from .types.streams_service import DeleteEventRequest +from .types.streams_service import DeleteSeriesRequest +from .types.streams_service import DeleteStreamRequest +from .types.streams_service import GenerateStreamHlsTokenRequest +from .types.streams_service import GenerateStreamHlsTokenResponse +from .types.streams_service import GetClusterRequest +from .types.streams_service import GetEventRequest +from .types.streams_service import GetSeriesRequest +from .types.streams_service import GetStreamRequest +from .types.streams_service import GetStreamThumbnailResponse +from .types.streams_service import ListClustersRequest +from .types.streams_service import ListClustersResponse +from .types.streams_service import ListEventsRequest +from .types.streams_service import ListEventsResponse +from .types.streams_service import ListSeriesRequest +from .types.streams_service import ListSeriesResponse +from .types.streams_service import ListStreamsRequest +from .types.streams_service import ListStreamsResponse +from .types.streams_service import MaterializeChannelRequest +from .types.streams_service import UpdateClusterRequest +from .types.streams_service import UpdateEventRequest +from .types.streams_service import UpdateSeriesRequest +from .types.streams_service import UpdateStreamRequest +from .types.warehouse import Annotation +from .types.warehouse import AnnotationMatchingResult +from .types.warehouse import AnnotationValue +from .types.warehouse import Asset +from .types.warehouse import BoolValue +from .types.warehouse import CircleArea +from .types.warehouse import ClipAssetRequest +from .types.warehouse import ClipAssetResponse +from .types.warehouse import Corpus +from .types.warehouse import CreateAnnotationRequest +from .types.warehouse import CreateAssetRequest +from .types.warehouse import CreateCorpusMetadata +from .types.warehouse import CreateCorpusRequest +from .types.warehouse import CreateDataSchemaRequest +from .types.warehouse import CreateSearchConfigRequest +from .types.warehouse import Criteria +from .types.warehouse import DataSchema +from .types.warehouse import DataSchemaDetails +from .types.warehouse import DateTimeRange +from .types.warehouse import DateTimeRangeArray +from .types.warehouse import DeleteAnnotationRequest +from .types.warehouse import DeleteAssetMetadata +from .types.warehouse import DeleteAssetRequest +from .types.warehouse import DeleteCorpusRequest +from .types.warehouse import DeleteDataSchemaRequest +from .types.warehouse import DeleteSearchConfigRequest +from .types.warehouse import FacetBucket +from .types.warehouse import FacetGroup +from .types.warehouse import FacetProperty +from .types.warehouse import FacetValue +from .types.warehouse import FloatRange +from .types.warehouse import FloatRangeArray +from .types.warehouse import GenerateHlsUriRequest +from .types.warehouse import GenerateHlsUriResponse +from .types.warehouse import GeoCoordinate +from .types.warehouse import GeoLocationArray +from .types.warehouse import GetAnnotationRequest +from .types.warehouse import GetAssetRequest +from .types.warehouse import GetCorpusRequest +from .types.warehouse import GetDataSchemaRequest +from .types.warehouse import GetSearchConfigRequest +from .types.warehouse import IngestAssetRequest +from .types.warehouse import IngestAssetResponse +from .types.warehouse import IntRange +from .types.warehouse import IntRangeArray +from .types.warehouse import ListAnnotationsRequest +from .types.warehouse import ListAnnotationsResponse +from .types.warehouse import ListAssetsRequest +from .types.warehouse import ListAssetsResponse +from .types.warehouse import ListCorporaRequest +from .types.warehouse import ListCorporaResponse +from .types.warehouse import ListDataSchemasRequest +from .types.warehouse import ListDataSchemasResponse +from .types.warehouse import ListSearchConfigsRequest +from .types.warehouse import ListSearchConfigsResponse +from .types.warehouse import Partition +from .types.warehouse import SearchAssetsRequest +from .types.warehouse import SearchAssetsResponse +from .types.warehouse import SearchConfig +from .types.warehouse import SearchCriteriaProperty +from .types.warehouse import SearchResultItem +from .types.warehouse import StringArray +from .types.warehouse import UpdateAnnotationRequest +from .types.warehouse import UpdateAssetRequest +from .types.warehouse import UpdateCorpusRequest +from .types.warehouse import UpdateDataSchemaRequest +from .types.warehouse import UpdateSearchConfigRequest +from .types.warehouse import UserSpecifiedAnnotation +from .types.warehouse import FacetBucketType + +__all__ = ( + 'AppPlatformAsyncClient', + 'LiveVideoAnalyticsAsyncClient', + 'StreamingServiceAsyncClient', + 'StreamsServiceAsyncClient', + 'WarehouseAsyncClient', +'AIEnabledDevicesInputConfig', +'AcceleratorType', +'AcquireLeaseRequest', +'AddApplicationStreamInputRequest', +'AddApplicationStreamInputResponse', +'Analysis', +'AnalysisDefinition', +'AnalyzerDefinition', +'Annotation', +'AnnotationMatchingResult', +'AnnotationValue', +'AppPlatformClient', +'AppPlatformCloudFunctionRequest', +'AppPlatformCloudFunctionResponse', +'AppPlatformEventBody', +'AppPlatformMetadata', +'Application', +'ApplicationConfigs', +'ApplicationInstance', +'ApplicationNodeAnnotation', +'ApplicationStreamInput', +'Asset', +'AttributeValue', +'AutoscalingMetricSpec', +'BigQueryConfig', +'BoolValue', +'Channel', +'CircleArea', +'ClassificationPredictionResult', +'ClipAssetRequest', +'ClipAssetResponse', +'Cluster', +'CommitRequest', +'ControlledMode', +'Corpus', +'CreateAnalysisRequest', +'CreateAnnotationRequest', +'CreateApplicationInstancesRequest', +'CreateApplicationInstancesResponse', +'CreateApplicationRequest', +'CreateAssetRequest', +'CreateClusterRequest', +'CreateCorpusMetadata', +'CreateCorpusRequest', +'CreateDataSchemaRequest', +'CreateDraftRequest', +'CreateEventRequest', +'CreateProcessorRequest', +'CreateSearchConfigRequest', +'CreateSeriesRequest', +'CreateStreamRequest', +'Criteria', +'CustomProcessorSourceInfo', +'DataSchema', +'DataSchemaDetails', +'DateTimeRange', +'DateTimeRangeArray', +'DedicatedResources', +'DeleteAnalysisRequest', +'DeleteAnnotationRequest', +'DeleteApplicationInstancesRequest', +'DeleteApplicationInstancesResponse', +'DeleteApplicationRequest', +'DeleteAssetMetadata', +'DeleteAssetRequest', +'DeleteClusterRequest', +'DeleteCorpusRequest', +'DeleteDataSchemaRequest', +'DeleteDraftRequest', +'DeleteEventRequest', +'DeleteProcessorRequest', +'DeleteSearchConfigRequest', +'DeleteSeriesRequest', +'DeleteStreamRequest', +'DeployApplicationRequest', +'DeployApplicationResponse', +'Draft', +'EagerMode', +'Event', +'EventUpdate', +'FacetBucket', +'FacetBucketType', +'FacetGroup', +'FacetProperty', +'FacetValue', +'FloatRange', +'FloatRangeArray', +'GcsSource', +'GeneralObjectDetectionConfig', +'GenerateHlsUriRequest', +'GenerateHlsUriResponse', +'GenerateStreamHlsTokenRequest', +'GenerateStreamHlsTokenResponse', +'GeoCoordinate', +'GeoLocationArray', +'GetAnalysisRequest', +'GetAnnotationRequest', +'GetApplicationRequest', +'GetAssetRequest', +'GetClusterRequest', +'GetCorpusRequest', +'GetDataSchemaRequest', +'GetDraftRequest', +'GetEventRequest', +'GetInstanceRequest', +'GetProcessorRequest', +'GetSearchConfigRequest', +'GetSeriesRequest', +'GetStreamRequest', +'GetStreamThumbnailResponse', +'GstreamerBufferDescriptor', +'ImageObjectDetectionPredictionResult', +'ImageSegmentationPredictionResult', +'IngestAssetRequest', +'IngestAssetResponse', +'Instance', +'IntRange', +'IntRangeArray', +'Lease', +'LeaseType', +'ListAnalysesRequest', +'ListAnalysesResponse', +'ListAnnotationsRequest', +'ListAnnotationsResponse', +'ListApplicationsRequest', +'ListApplicationsResponse', +'ListAssetsRequest', +'ListAssetsResponse', +'ListClustersRequest', +'ListClustersResponse', +'ListCorporaRequest', +'ListCorporaResponse', +'ListDataSchemasRequest', +'ListDataSchemasResponse', +'ListDraftsRequest', +'ListDraftsResponse', +'ListEventsRequest', +'ListEventsResponse', +'ListInstancesRequest', +'ListInstancesResponse', +'ListPrebuiltProcessorsRequest', +'ListPrebuiltProcessorsResponse', +'ListProcessorsRequest', +'ListProcessorsResponse', +'ListSearchConfigsRequest', +'ListSearchConfigsResponse', +'ListSeriesRequest', +'ListSeriesResponse', +'ListStreamsRequest', +'ListStreamsResponse', +'LiveVideoAnalyticsClient', +'MachineSpec', +'MaterializeChannelRequest', +'MediaWarehouseConfig', +'ModelType', +'Node', +'NormalizedPolygon', +'NormalizedPolyline', +'NormalizedVertex', +'ObjectDetectionPredictionResult', +'OccupancyCountConfig', +'OccupancyCountingPredictionResult', +'OperationMetadata', +'Packet', +'PacketHeader', +'PacketType', +'Partition', +'PersonBlurConfig', +'PersonVehicleDetectionConfig', +'PersonalProtectiveEquipmentDetectionConfig', +'PersonalProtectiveEquipmentDetectionOutput', +'Processor', +'ProcessorConfig', +'ProcessorIOSpec', +'RawImageDescriptor', +'ReceiveEventsControlResponse', +'ReceiveEventsRequest', +'ReceiveEventsResponse', +'ReceivePacketsControlResponse', +'ReceivePacketsRequest', +'ReceivePacketsResponse', +'ReleaseLeaseRequest', +'ReleaseLeaseResponse', +'RemoveApplicationStreamInputRequest', +'RemoveApplicationStreamInputResponse', +'RenewLeaseRequest', +'RequestMetadata', +'ResourceAnnotations', +'SearchAssetsRequest', +'SearchAssetsResponse', +'SearchConfig', +'SearchCriteriaProperty', +'SearchResultItem', +'SendPacketsRequest', +'SendPacketsResponse', +'Series', +'SeriesMetadata', +'ServerMetadata', +'Stream', +'StreamAnnotation', +'StreamAnnotationType', +'StreamAnnotations', +'StreamWithAnnotation', +'StreamingServiceClient', +'StreamsServiceClient', +'StringArray', +'UndeployApplicationRequest', +'UndeployApplicationResponse', +'UpdateAnalysisRequest', +'UpdateAnnotationRequest', +'UpdateApplicationInstancesRequest', +'UpdateApplicationInstancesResponse', +'UpdateApplicationRequest', +'UpdateApplicationStreamInputRequest', +'UpdateApplicationStreamInputResponse', +'UpdateAssetRequest', +'UpdateClusterRequest', +'UpdateCorpusRequest', +'UpdateDataSchemaRequest', +'UpdateDraftRequest', +'UpdateEventRequest', +'UpdateProcessorRequest', +'UpdateSearchConfigRequest', +'UpdateSeriesRequest', +'UpdateStreamRequest', +'UserSpecifiedAnnotation', +'VertexAutoMLVideoConfig', +'VertexAutoMLVisionConfig', +'VertexCustomConfig', +'VideoActionRecognitionPredictionResult', +'VideoClassificationPredictionResult', +'VideoObjectTrackingPredictionResult', +'VideoStreamInputConfig', +'WarehouseClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/gapic_metadata.json b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/gapic_metadata.json new file mode 100644 index 000000000000..32e54a2ad06a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/gapic_metadata.json @@ -0,0 +1,1424 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.visionai_v1alpha1", + "protoPackage": "google.cloud.visionai.v1alpha1", + "schema": "1.0", + "services": { + "AppPlatform": { + "clients": { + "grpc": { + "libraryClient": "AppPlatformClient", + "rpcs": { + "AddApplicationStreamInput": { + "methods": [ + "add_application_stream_input" + ] + }, + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "CreateApplicationInstances": { + "methods": [ + "create_application_instances" + ] + }, + "CreateDraft": { + "methods": [ + "create_draft" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteApplication": { + "methods": [ + "delete_application" + ] + }, + "DeleteApplicationInstances": { + "methods": [ + "delete_application_instances" + ] + }, + "DeleteDraft": { + "methods": [ + "delete_draft" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeployApplication": { + "methods": [ + "deploy_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "GetDraft": { + "methods": [ + "get_draft" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "ListApplications": { + "methods": [ + "list_applications" + ] + }, + "ListDrafts": { + "methods": [ + "list_drafts" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListPrebuiltProcessors": { + "methods": [ + "list_prebuilt_processors" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "RemoveApplicationStreamInput": { + "methods": [ + "remove_application_stream_input" + ] + }, + "UndeployApplication": { + "methods": [ + "undeploy_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + }, + "UpdateApplicationInstances": { + "methods": [ + "update_application_instances" + ] + }, + "UpdateApplicationStreamInput": { + "methods": [ + "update_application_stream_input" + ] + }, + "UpdateDraft": { + "methods": [ + "update_draft" + ] + }, + "UpdateProcessor": { + "methods": [ + "update_processor" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AppPlatformAsyncClient", + "rpcs": { + "AddApplicationStreamInput": { + "methods": [ + "add_application_stream_input" + ] + }, + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "CreateApplicationInstances": { + "methods": [ + "create_application_instances" + ] + }, + "CreateDraft": { + "methods": [ + "create_draft" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteApplication": { + "methods": [ + "delete_application" + ] + }, + "DeleteApplicationInstances": { + "methods": [ + "delete_application_instances" + ] + }, + "DeleteDraft": { + "methods": [ + "delete_draft" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeployApplication": { + "methods": [ + "deploy_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "GetDraft": { + "methods": [ + "get_draft" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "ListApplications": { + "methods": [ + "list_applications" + ] + }, + "ListDrafts": { + "methods": [ + "list_drafts" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListPrebuiltProcessors": { + "methods": [ + "list_prebuilt_processors" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "RemoveApplicationStreamInput": { + "methods": [ + "remove_application_stream_input" + ] + }, + "UndeployApplication": { + "methods": [ + "undeploy_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + }, + "UpdateApplicationInstances": { + "methods": [ + "update_application_instances" + ] + }, + "UpdateApplicationStreamInput": { + "methods": [ + "update_application_stream_input" + ] + }, + "UpdateDraft": { + "methods": [ + "update_draft" + ] + }, + "UpdateProcessor": { + "methods": [ + "update_processor" + ] + } + } + }, + "rest": { + "libraryClient": "AppPlatformClient", + "rpcs": { + "AddApplicationStreamInput": { + "methods": [ + "add_application_stream_input" + ] + }, + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "CreateApplicationInstances": { + "methods": [ + "create_application_instances" + ] + }, + "CreateDraft": { + "methods": [ + "create_draft" + ] + }, + "CreateProcessor": { + "methods": [ + "create_processor" + ] + }, + "DeleteApplication": { + "methods": [ + "delete_application" + ] + }, + "DeleteApplicationInstances": { + "methods": [ + "delete_application_instances" + ] + }, + "DeleteDraft": { + "methods": [ + "delete_draft" + ] + }, + "DeleteProcessor": { + "methods": [ + "delete_processor" + ] + }, + "DeployApplication": { + "methods": [ + "deploy_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "GetDraft": { + "methods": [ + "get_draft" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetProcessor": { + "methods": [ + "get_processor" + ] + }, + "ListApplications": { + "methods": [ + "list_applications" + ] + }, + "ListDrafts": { + "methods": [ + "list_drafts" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListPrebuiltProcessors": { + "methods": [ + "list_prebuilt_processors" + ] + }, + "ListProcessors": { + "methods": [ + "list_processors" + ] + }, + "RemoveApplicationStreamInput": { + "methods": [ + "remove_application_stream_input" + ] + }, + "UndeployApplication": { + "methods": [ + "undeploy_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + }, + "UpdateApplicationInstances": { + "methods": [ + "update_application_instances" + ] + }, + "UpdateApplicationStreamInput": { + "methods": [ + "update_application_stream_input" + ] + }, + "UpdateDraft": { + "methods": [ + "update_draft" + ] + }, + "UpdateProcessor": { + "methods": [ + "update_processor" + ] + } + } + } + } + }, + "LiveVideoAnalytics": { + "clients": { + "grpc": { + "libraryClient": "LiveVideoAnalyticsClient", + "rpcs": { + "CreateAnalysis": { + "methods": [ + "create_analysis" + ] + }, + "DeleteAnalysis": { + "methods": [ + "delete_analysis" + ] + }, + "GetAnalysis": { + "methods": [ + "get_analysis" + ] + }, + "ListAnalyses": { + "methods": [ + "list_analyses" + ] + }, + "UpdateAnalysis": { + "methods": [ + "update_analysis" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LiveVideoAnalyticsAsyncClient", + "rpcs": { + "CreateAnalysis": { + "methods": [ + "create_analysis" + ] + }, + "DeleteAnalysis": { + "methods": [ + "delete_analysis" + ] + }, + "GetAnalysis": { + "methods": [ + "get_analysis" + ] + }, + "ListAnalyses": { + "methods": [ + "list_analyses" + ] + }, + "UpdateAnalysis": { + "methods": [ + "update_analysis" + ] + } + } + }, + "rest": { + "libraryClient": "LiveVideoAnalyticsClient", + "rpcs": { + "CreateAnalysis": { + "methods": [ + "create_analysis" + ] + }, + "DeleteAnalysis": { + "methods": [ + "delete_analysis" + ] + }, + "GetAnalysis": { + "methods": [ + "get_analysis" + ] + }, + "ListAnalyses": { + "methods": [ + "list_analyses" + ] + }, + "UpdateAnalysis": { + "methods": [ + "update_analysis" + ] + } + } + } + } + }, + "StreamingService": { + "clients": { + "grpc": { + "libraryClient": "StreamingServiceClient", + "rpcs": { + "AcquireLease": { + "methods": [ + "acquire_lease" + ] + }, + "ReceiveEvents": { + "methods": [ + "receive_events" + ] + }, + "ReceivePackets": { + "methods": [ + "receive_packets" + ] + }, + "ReleaseLease": { + "methods": [ + "release_lease" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "SendPackets": { + "methods": [ + "send_packets" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StreamingServiceAsyncClient", + "rpcs": { + "AcquireLease": { + "methods": [ + "acquire_lease" + ] + }, + "ReceiveEvents": { + "methods": [ + "receive_events" + ] + }, + "ReceivePackets": { + "methods": [ + "receive_packets" + ] + }, + "ReleaseLease": { + "methods": [ + "release_lease" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "SendPackets": { + "methods": [ + "send_packets" + ] + } + } + }, + "rest": { + "libraryClient": "StreamingServiceClient", + "rpcs": { + "AcquireLease": { + "methods": [ + "acquire_lease" + ] + }, + "ReceiveEvents": { + "methods": [ + "receive_events" + ] + }, + "ReceivePackets": { + "methods": [ + "receive_packets" + ] + }, + "ReleaseLease": { + "methods": [ + "release_lease" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "SendPackets": { + "methods": [ + "send_packets" + ] + } + } + } + } + }, + "StreamsService": { + "clients": { + "grpc": { + "libraryClient": "StreamsServiceClient", + "rpcs": { + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateEvent": { + "methods": [ + "create_event" + ] + }, + "CreateSeries": { + "methods": [ + "create_series" + ] + }, + "CreateStream": { + "methods": [ + "create_stream" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteEvent": { + "methods": [ + "delete_event" + ] + }, + "DeleteSeries": { + "methods": [ + "delete_series" + ] + }, + "DeleteStream": { + "methods": [ + "delete_stream" + ] + }, + "GenerateStreamHlsToken": { + "methods": [ + "generate_stream_hls_token" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetEvent": { + "methods": [ + "get_event" + ] + }, + "GetSeries": { + "methods": [ + "get_series" + ] + }, + "GetStream": { + "methods": [ + "get_stream" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListEvents": { + "methods": [ + "list_events" + ] + }, + "ListSeries": { + "methods": [ + "list_series" + ] + }, + "ListStreams": { + "methods": [ + "list_streams" + ] + }, + "MaterializeChannel": { + "methods": [ + "materialize_channel" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateEvent": { + "methods": [ + "update_event" + ] + }, + "UpdateSeries": { + "methods": [ + "update_series" + ] + }, + "UpdateStream": { + "methods": [ + "update_stream" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StreamsServiceAsyncClient", + "rpcs": { + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateEvent": { + "methods": [ + "create_event" + ] + }, + "CreateSeries": { + "methods": [ + "create_series" + ] + }, + "CreateStream": { + "methods": [ + "create_stream" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteEvent": { + "methods": [ + "delete_event" + ] + }, + "DeleteSeries": { + "methods": [ + "delete_series" + ] + }, + "DeleteStream": { + "methods": [ + "delete_stream" + ] + }, + "GenerateStreamHlsToken": { + "methods": [ + "generate_stream_hls_token" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetEvent": { + "methods": [ + "get_event" + ] + }, + "GetSeries": { + "methods": [ + "get_series" + ] + }, + "GetStream": { + "methods": [ + "get_stream" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListEvents": { + "methods": [ + "list_events" + ] + }, + "ListSeries": { + "methods": [ + "list_series" + ] + }, + "ListStreams": { + "methods": [ + "list_streams" + ] + }, + "MaterializeChannel": { + "methods": [ + "materialize_channel" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateEvent": { + "methods": [ + "update_event" + ] + }, + "UpdateSeries": { + "methods": [ + "update_series" + ] + }, + "UpdateStream": { + "methods": [ + "update_stream" + ] + } + } + }, + "rest": { + "libraryClient": "StreamsServiceClient", + "rpcs": { + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateEvent": { + "methods": [ + "create_event" + ] + }, + "CreateSeries": { + "methods": [ + "create_series" + ] + }, + "CreateStream": { + "methods": [ + "create_stream" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteEvent": { + "methods": [ + "delete_event" + ] + }, + "DeleteSeries": { + "methods": [ + "delete_series" + ] + }, + "DeleteStream": { + "methods": [ + "delete_stream" + ] + }, + "GenerateStreamHlsToken": { + "methods": [ + "generate_stream_hls_token" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetEvent": { + "methods": [ + "get_event" + ] + }, + "GetSeries": { + "methods": [ + "get_series" + ] + }, + "GetStream": { + "methods": [ + "get_stream" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListEvents": { + "methods": [ + "list_events" + ] + }, + "ListSeries": { + "methods": [ + "list_series" + ] + }, + "ListStreams": { + "methods": [ + "list_streams" + ] + }, + "MaterializeChannel": { + "methods": [ + "materialize_channel" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateEvent": { + "methods": [ + "update_event" + ] + }, + "UpdateSeries": { + "methods": [ + "update_series" + ] + }, + "UpdateStream": { + "methods": [ + "update_stream" + ] + } + } + } + } + }, + "Warehouse": { + "clients": { + "grpc": { + "libraryClient": "WarehouseClient", + "rpcs": { + "ClipAsset": { + "methods": [ + "clip_asset" + ] + }, + "CreateAnnotation": { + "methods": [ + "create_annotation" + ] + }, + "CreateAsset": { + "methods": [ + "create_asset" + ] + }, + "CreateCorpus": { + "methods": [ + "create_corpus" + ] + }, + "CreateDataSchema": { + "methods": [ + "create_data_schema" + ] + }, + "CreateSearchConfig": { + "methods": [ + "create_search_config" + ] + }, + "DeleteAnnotation": { + "methods": [ + "delete_annotation" + ] + }, + "DeleteAsset": { + "methods": [ + "delete_asset" + ] + }, + "DeleteCorpus": { + "methods": [ + "delete_corpus" + ] + }, + "DeleteDataSchema": { + "methods": [ + "delete_data_schema" + ] + }, + "DeleteSearchConfig": { + "methods": [ + "delete_search_config" + ] + }, + "GenerateHlsUri": { + "methods": [ + "generate_hls_uri" + ] + }, + "GetAnnotation": { + "methods": [ + "get_annotation" + ] + }, + "GetAsset": { + "methods": [ + "get_asset" + ] + }, + "GetCorpus": { + "methods": [ + "get_corpus" + ] + }, + "GetDataSchema": { + "methods": [ + "get_data_schema" + ] + }, + "GetSearchConfig": { + "methods": [ + "get_search_config" + ] + }, + "IngestAsset": { + "methods": [ + "ingest_asset" + ] + }, + "ListAnnotations": { + "methods": [ + "list_annotations" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListCorpora": { + "methods": [ + "list_corpora" + ] + }, + "ListDataSchemas": { + "methods": [ + "list_data_schemas" + ] + }, + "ListSearchConfigs": { + "methods": [ + "list_search_configs" + ] + }, + "SearchAssets": { + "methods": [ + "search_assets" + ] + }, + "UpdateAnnotation": { + "methods": [ + "update_annotation" + ] + }, + "UpdateAsset": { + "methods": [ + "update_asset" + ] + }, + "UpdateCorpus": { + "methods": [ + "update_corpus" + ] + }, + "UpdateDataSchema": { + "methods": [ + "update_data_schema" + ] + }, + "UpdateSearchConfig": { + "methods": [ + "update_search_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WarehouseAsyncClient", + "rpcs": { + "ClipAsset": { + "methods": [ + "clip_asset" + ] + }, + "CreateAnnotation": { + "methods": [ + "create_annotation" + ] + }, + "CreateAsset": { + "methods": [ + "create_asset" + ] + }, + "CreateCorpus": { + "methods": [ + "create_corpus" + ] + }, + "CreateDataSchema": { + "methods": [ + "create_data_schema" + ] + }, + "CreateSearchConfig": { + "methods": [ + "create_search_config" + ] + }, + "DeleteAnnotation": { + "methods": [ + "delete_annotation" + ] + }, + "DeleteAsset": { + "methods": [ + "delete_asset" + ] + }, + "DeleteCorpus": { + "methods": [ + "delete_corpus" + ] + }, + "DeleteDataSchema": { + "methods": [ + "delete_data_schema" + ] + }, + "DeleteSearchConfig": { + "methods": [ + "delete_search_config" + ] + }, + "GenerateHlsUri": { + "methods": [ + "generate_hls_uri" + ] + }, + "GetAnnotation": { + "methods": [ + "get_annotation" + ] + }, + "GetAsset": { + "methods": [ + "get_asset" + ] + }, + "GetCorpus": { + "methods": [ + "get_corpus" + ] + }, + "GetDataSchema": { + "methods": [ + "get_data_schema" + ] + }, + "GetSearchConfig": { + "methods": [ + "get_search_config" + ] + }, + "IngestAsset": { + "methods": [ + "ingest_asset" + ] + }, + "ListAnnotations": { + "methods": [ + "list_annotations" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListCorpora": { + "methods": [ + "list_corpora" + ] + }, + "ListDataSchemas": { + "methods": [ + "list_data_schemas" + ] + }, + "ListSearchConfigs": { + "methods": [ + "list_search_configs" + ] + }, + "SearchAssets": { + "methods": [ + "search_assets" + ] + }, + "UpdateAnnotation": { + "methods": [ + "update_annotation" + ] + }, + "UpdateAsset": { + "methods": [ + "update_asset" + ] + }, + "UpdateCorpus": { + "methods": [ + "update_corpus" + ] + }, + "UpdateDataSchema": { + "methods": [ + "update_data_schema" + ] + }, + "UpdateSearchConfig": { + "methods": [ + "update_search_config" + ] + } + } + }, + "rest": { + "libraryClient": "WarehouseClient", + "rpcs": { + "ClipAsset": { + "methods": [ + "clip_asset" + ] + }, + "CreateAnnotation": { + "methods": [ + "create_annotation" + ] + }, + "CreateAsset": { + "methods": [ + "create_asset" + ] + }, + "CreateCorpus": { + "methods": [ + "create_corpus" + ] + }, + "CreateDataSchema": { + "methods": [ + "create_data_schema" + ] + }, + "CreateSearchConfig": { + "methods": [ + "create_search_config" + ] + }, + "DeleteAnnotation": { + "methods": [ + "delete_annotation" + ] + }, + "DeleteAsset": { + "methods": [ + "delete_asset" + ] + }, + "DeleteCorpus": { + "methods": [ + "delete_corpus" + ] + }, + "DeleteDataSchema": { + "methods": [ + "delete_data_schema" + ] + }, + "DeleteSearchConfig": { + "methods": [ + "delete_search_config" + ] + }, + "GenerateHlsUri": { + "methods": [ + "generate_hls_uri" + ] + }, + "GetAnnotation": { + "methods": [ + "get_annotation" + ] + }, + "GetAsset": { + "methods": [ + "get_asset" + ] + }, + "GetCorpus": { + "methods": [ + "get_corpus" + ] + }, + "GetDataSchema": { + "methods": [ + "get_data_schema" + ] + }, + "GetSearchConfig": { + "methods": [ + "get_search_config" + ] + }, + "IngestAsset": { + "methods": [ + "ingest_asset" + ] + }, + "ListAnnotations": { + "methods": [ + "list_annotations" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListCorpora": { + "methods": [ + "list_corpora" + ] + }, + "ListDataSchemas": { + "methods": [ + "list_data_schemas" + ] + }, + "ListSearchConfigs": { + "methods": [ + "list_search_configs" + ] + }, + "SearchAssets": { + "methods": [ + "search_assets" + ] + }, + "UpdateAnnotation": { + "methods": [ + "update_annotation" + ] + }, + "UpdateAsset": { + "methods": [ + "update_asset" + ] + }, + "UpdateCorpus": { + "methods": [ + "update_corpus" + ] + }, + "UpdateDataSchema": { + "methods": [ + "update_data_schema" + ] + }, + "UpdateSearchConfig": { + "methods": [ + "update_search_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/gapic_version.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/py.typed b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/py.typed new file mode 100644 index 000000000000..7b2e82d731c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-visionai package uses inline types. diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/__init__.py new file mode 100644 index 000000000000..0a8bf703dca7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 AppPlatformClient +from .async_client import AppPlatformAsyncClient + +__all__ = ( + 'AppPlatformClient', + 'AppPlatformAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/async_client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/async_client.py new file mode 100644 index 000000000000..52e17988ff0f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/async_client.py @@ -0,0 +1,3996 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.app_platform import pagers +from google.cloud.visionai_v1alpha1.types import annotations +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AppPlatformTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AppPlatformGrpcAsyncIOTransport +from .client import AppPlatformClient + + +class AppPlatformAsyncClient: + """Service describing handlers for resources""" + + _client: AppPlatformClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AppPlatformClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AppPlatformClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AppPlatformClient._DEFAULT_UNIVERSE + + application_path = staticmethod(AppPlatformClient.application_path) + parse_application_path = staticmethod(AppPlatformClient.parse_application_path) + draft_path = staticmethod(AppPlatformClient.draft_path) + parse_draft_path = staticmethod(AppPlatformClient.parse_draft_path) + instance_path = staticmethod(AppPlatformClient.instance_path) + parse_instance_path = staticmethod(AppPlatformClient.parse_instance_path) + processor_path = staticmethod(AppPlatformClient.processor_path) + parse_processor_path = staticmethod(AppPlatformClient.parse_processor_path) + stream_path = staticmethod(AppPlatformClient.stream_path) + parse_stream_path = staticmethod(AppPlatformClient.parse_stream_path) + common_billing_account_path = staticmethod(AppPlatformClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AppPlatformClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AppPlatformClient.common_folder_path) + parse_common_folder_path = staticmethod(AppPlatformClient.parse_common_folder_path) + common_organization_path = staticmethod(AppPlatformClient.common_organization_path) + parse_common_organization_path = staticmethod(AppPlatformClient.parse_common_organization_path) + common_project_path = staticmethod(AppPlatformClient.common_project_path) + parse_common_project_path = staticmethod(AppPlatformClient.parse_common_project_path) + common_location_path = staticmethod(AppPlatformClient.common_location_path) + parse_common_location_path = staticmethod(AppPlatformClient.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: + AppPlatformAsyncClient: The constructed client. + """ + return AppPlatformClient.from_service_account_info.__func__(AppPlatformAsyncClient, 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: + AppPlatformAsyncClient: The constructed client. + """ + return AppPlatformClient.from_service_account_file.__func__(AppPlatformAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return AppPlatformClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AppPlatformTransport: + """Returns the transport used by the client instance. + + Returns: + AppPlatformTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(AppPlatformClient).get_transport_class, type(AppPlatformClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AppPlatformTransport, Callable[..., AppPlatformTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the app platform async 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 (Optional[Union[str,AppPlatformTransport,Callable[..., AppPlatformTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AppPlatformTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = AppPlatformClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_applications(self, + request: Optional[Union[platform.ListApplicationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApplicationsAsyncPager: + r"""Lists Applications in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_applications(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListApplicationsRequest, dict]]): + The request object. Message for requesting list of + Applications. + parent (:class:`str`): + Required. Parent value for + ListApplicationsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListApplicationsAsyncPager: + Message for response to listing + Applications. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListApplicationsRequest): + request = platform.ListApplicationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_applications] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListApplicationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_application(self, + request: Optional[Union[platform.GetApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Application: + r"""Gets details of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_application(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetApplicationRequest, dict]]): + The request object. Message for getting a Application. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Application: + Message describing Application object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetApplicationRequest): + request = platform.GetApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.get_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_application(self, + request: Optional[Union[platform.CreateApplicationRequest, dict]] = None, + *, + parent: Optional[str] = None, + application: Optional[platform.Application] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Application in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateApplicationRequest, dict]]): + The request object. Message for creating a Application. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application (:class:`google.cloud.visionai_v1alpha1.types.Application`): + Required. The resource being created. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, application]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationRequest): + request = platform.CreateApplicationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if application is not None: + request.application = application + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_application(self, + request: Optional[Union[platform.UpdateApplicationRequest, dict]] = None, + *, + application: Optional[platform.Application] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateApplicationRequest, dict]]): + The request object. Message for updating an Application. + application (:class:`google.cloud.visionai_v1alpha1.types.Application`): + Required. The resource being updated. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Application resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([application, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationRequest): + request = platform.UpdateApplicationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if application is not None: + request.application = application + 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._client._transport._wrapped_methods[self._client._transport.update_application] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("application.name", request.application.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_application(self, + request: Optional[Union[platform.DeleteApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteApplicationRequest, dict]]): + The request object. Message for deleting an Application. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationRequest): + request = platform.DeleteApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.delete_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def deploy_application(self, + request: Optional[Union[platform.DeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_deploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeployApplicationRequest, dict]]): + The request object. Message for deploying an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.DeployApplicationResponse` RPC Request Messages. + Message for DeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeployApplicationRequest): + request = platform.DeployApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.deploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.DeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def undeploy_application(self, + request: Optional[Union[platform.UndeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Undeploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_undeploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UndeployApplicationRequest, dict]]): + The request object. Message for undeploying an + Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.UndeployApplicationResponse` + Message for UndeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UndeployApplicationRequest): + request = platform.UndeployApplicationRequest(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._client._transport._wrapped_methods[self._client._transport.undeploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.UndeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def add_application_stream_input(self, + request: Optional[Union[platform.AddApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_add_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.AddApplicationStreamInputRequest, dict]]): + The request object. Message for adding stream input to an + Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.AddApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.AddApplicationStreamInputRequest): + request = platform.AddApplicationStreamInputRequest(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._client._transport._wrapped_methods[self._client._transport.add_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.AddApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def remove_application_stream_input(self, + request: Optional[Union[platform.RemoveApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.RemoveApplicationStreamInputRequest, dict]]): + The request object. Message for removing stream input + from an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.RemoveApplicationStreamInputResponse` + Message for RemoveApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.RemoveApplicationStreamInputRequest): + request = platform.RemoveApplicationStreamInputRequest(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._client._transport._wrapped_methods[self._client._transport.remove_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.RemoveApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_application_stream_input(self, + request: Optional[Union[platform.UpdateApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateApplicationStreamInputRequest, dict]]): + The request object. Message for updating stream input to + an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.UpdateApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationStreamInputRequest): + request = platform.UpdateApplicationStreamInputRequest(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._client._transport._wrapped_methods[self._client._transport.update_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.UpdateApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_instances(self, + request: Optional[Union[platform.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstancesAsyncPager: + r"""Lists Instances in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListInstancesRequest, dict]]): + The request object. Message for requesting list of + Instances. + parent (:class:`str`): + Required. Parent value for + ListInstancesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListInstancesAsyncPager: + Message for response to listing + Instances. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListInstancesRequest): + request = platform.ListInstancesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_instance(self, + request: Optional[Union[platform.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_instance(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetInstanceRequest, dict]]): + The request object. Message for getting a Instance. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Instance: + Message describing Instance object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetInstanceRequest): + request = platform.GetInstanceRequest(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._client._transport._wrapped_methods[self._client._transport.get_instance] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_application_instances(self, + request: Optional[Union[platform.CreateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application_instances = visionai_v1alpha1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateApplicationInstancesRequest, dict]]): + The request object. Message for adding stream input to an + Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.CreateApplicationInstancesResponse` + Message for CreateApplicationInstance Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationInstancesRequest): + request = platform.CreateApplicationInstancesRequest(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._client._transport._wrapped_methods[self._client._transport.create_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.CreateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_application_instances(self, + request: Optional[Union[platform.DeleteApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteApplicationInstancesRequest, dict]]): + The request object. Message for removing stream input + from an Application. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Instance` + Message describing Instance object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationInstancesRequest): + request = platform.DeleteApplicationInstancesRequest(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._client._transport._wrapped_methods[self._client._transport.delete_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Instance, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_application_instances(self, + request: Optional[Union[platform.UpdateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + application_instances: Optional[MutableSequence[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest, dict]]): + The request object. Message for updating an + ApplicationInstance. + name (:class:`str`): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application_instances (:class:`MutableSequence[google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]`): + + This corresponds to the ``application_instances`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesResponse` + Message for UpdateApplicationInstances Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, application_instances]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationInstancesRequest): + request = platform.UpdateApplicationInstancesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if application_instances: + request.application_instances.extend(application_instances) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.UpdateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_drafts(self, + request: Optional[Union[platform.ListDraftsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDraftsAsyncPager: + r"""Lists Drafts in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_drafts(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListDraftsRequest, dict]]): + The request object. Message for requesting list of + Drafts. + parent (:class:`str`): + Required. Parent value for + ListDraftsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListDraftsAsyncPager: + Message for response to listing + Drafts. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListDraftsRequest): + request = platform.ListDraftsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_drafts] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListDraftsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_draft(self, + request: Optional[Union[platform.GetDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Draft: + r"""Gets details of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = await client.get_draft(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetDraftRequest, dict]]): + The request object. Message for getting a Draft. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Draft: + Message describing Draft object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetDraftRequest): + request = platform.GetDraftRequest(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._client._transport._wrapped_methods[self._client._transport.get_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_draft(self, + request: Optional[Union[platform.CreateDraftRequest, dict]] = None, + *, + parent: Optional[str] = None, + draft: Optional[platform.Draft] = None, + draft_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Draft in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateDraftRequest, dict]]): + The request object. Message for creating a Draft. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft (:class:`google.cloud.visionai_v1alpha1.types.Draft`): + Required. The resource being created. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``draft_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Draft` + Message describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, draft, draft_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateDraftRequest): + request = platform.CreateDraftRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if draft is not None: + request.draft = draft + if draft_id is not None: + request.draft_id = draft_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_draft(self, + request: Optional[Union[platform.UpdateDraftRequest, dict]] = None, + *, + draft: Optional[platform.Draft] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateDraftRequest, dict]]): + The request object. Message for updating an Draft. + draft (:class:`google.cloud.visionai_v1alpha1.types.Draft`): + Required. The resource being updated. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Draft` + Message describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([draft, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateDraftRequest): + request = platform.UpdateDraftRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if draft is not None: + request.draft = draft + 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._client._transport._wrapped_methods[self._client._transport.update_draft] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("draft.name", request.draft.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_draft(self, + request: Optional[Union[platform.DeleteDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteDraftRequest, dict]]): + The request object. Message for deleting an Draft. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteDraftRequest): + request = platform.DeleteDraftRequest(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._client._transport._wrapped_methods[self._client._transport.delete_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_processors(self, + request: Optional[Union[platform.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsAsyncPager: + r"""Lists Processors in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListProcessorsRequest, dict]]): + The request object. Message for requesting list of + Processors. + parent (:class:`str`): + Required. Parent value for + ListProcessorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListProcessorsAsyncPager: + Message for response to listing + Processors. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListProcessorsRequest): + request = platform.ListProcessorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListProcessorsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_prebuilt_processors(self, + request: Optional[Union[platform.ListPrebuiltProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.ListPrebuiltProcessorsResponse: + r"""ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsRequest, dict]]): + The request object. Request Message for listing Prebuilt + Processors. + parent (:class:`str`): + Required. Parent path. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsResponse: + Response Message for listing Prebuilt + Processors. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListPrebuiltProcessorsRequest): + request = platform.ListPrebuiltProcessorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_prebuilt_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_processor(self, + request: Optional[Union[platform.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Processor: + r"""Gets details of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetProcessorRequest, dict]]): + The request object. Message for getting a Processor. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Processor: + Message describing Processor object. + Next ID: 18 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetProcessorRequest): + request = platform.GetProcessorRequest(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._client._transport._wrapped_methods[self._client._transport.get_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_processor(self, + request: Optional[Union[platform.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[platform.Processor] = None, + processor_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Processor in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateProcessorRequest, dict]]): + The request object. Message for creating a Processor. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (:class:`google.cloud.visionai_v1alpha1.types.Processor`): + Required. The resource being created. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``processor_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Processor` Message describing Processor object. + Next ID: 18 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, processor, processor_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateProcessorRequest): + request = platform.CreateProcessorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + if processor_id is not None: + request.processor_id = processor_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_processor(self, + request: Optional[Union[platform.UpdateProcessorRequest, dict]] = None, + *, + processor: Optional[platform.Processor] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateProcessorRequest, dict]]): + The request object. Message for updating a Processor. + processor (:class:`google.cloud.visionai_v1alpha1.types.Processor`): + Required. The resource being updated. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Processor resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Processor` Message describing Processor object. + Next ID: 18 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([processor, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateProcessorRequest): + request = platform.UpdateProcessorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if processor is not None: + request.processor = processor + 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._client._transport._wrapped_methods[self._client._transport.update_processor] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("processor.name", request.processor.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_processor(self, + request: Optional[Union[platform.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteProcessorRequest, dict]]): + The request object. Message for deleting a Processor. + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteProcessorRequest): + request = platform.DeleteProcessorRequest(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._client._transport._wrapped_methods[self._client._transport.delete_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AppPlatformAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AppPlatformAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/client.py new file mode 100644 index 000000000000..9d868e599939 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/client.py @@ -0,0 +1,4358 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.app_platform import pagers +from google.cloud.visionai_v1alpha1.types import annotations +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AppPlatformTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AppPlatformGrpcTransport +from .transports.grpc_asyncio import AppPlatformGrpcAsyncIOTransport +from .transports.rest import AppPlatformRestTransport + + +class AppPlatformClientMeta(type): + """Metaclass for the AppPlatform 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[AppPlatformTransport]] + _transport_registry["grpc"] = AppPlatformGrpcTransport + _transport_registry["grpc_asyncio"] = AppPlatformGrpcAsyncIOTransport + _transport_registry["rest"] = AppPlatformRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AppPlatformTransport]: + """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 AppPlatformClient(metaclass=AppPlatformClientMeta): + """Service describing handlers for resources""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + AppPlatformClient: 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: + AppPlatformClient: 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) -> AppPlatformTransport: + """Returns the transport used by the client instance. + + Returns: + AppPlatformTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def application_path(project: str,location: str,application: str,) -> str: + """Returns a fully-qualified application string.""" + return "projects/{project}/locations/{location}/applications/{application}".format(project=project, location=location, application=application, ) + + @staticmethod + def parse_application_path(path: str) -> Dict[str,str]: + """Parses a application path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/applications/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def draft_path(project: str,location: str,application: str,draft: str,) -> str: + """Returns a fully-qualified draft string.""" + return "projects/{project}/locations/{location}/applications/{application}/drafts/{draft}".format(project=project, location=location, application=application, draft=draft, ) + + @staticmethod + def parse_draft_path(path: str) -> Dict[str,str]: + """Parses a draft path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/applications/(?P.+?)/drafts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def instance_path(project: str,location: str,application: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/applications/{application}/instances/{instance}".format(project=project, location=location, application=application, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/applications/(?P.+?)/instances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def processor_path(project: str,location: str,processor: str,) -> str: + """Returns a fully-qualified processor string.""" + return "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + + @staticmethod + def parse_processor_path(path: str) -> Dict[str,str]: + """Parses a processor path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def stream_path(project: str,location: str,cluster: str,stream: str,) -> str: + """Returns a fully-qualified stream string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + + @staticmethod + def parse_stream_path(path: str) -> Dict[str,str]: + """Parses a stream path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/streams/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AppPlatformClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AppPlatformClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AppPlatformClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = AppPlatformClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + AppPlatformClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AppPlatformTransport, Callable[..., AppPlatformTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the app platform 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 (Optional[Union[str,AppPlatformTransport,Callable[..., AppPlatformTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AppPlatformTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AppPlatformClient._read_environment_variables() + self._client_cert_source = AppPlatformClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AppPlatformClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AppPlatformTransport) + if transport_provided: + # transport is a AppPlatformTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AppPlatformTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AppPlatformClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AppPlatformTransport], Callable[..., AppPlatformTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AppPlatformTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_applications(self, + request: Optional[Union[platform.ListApplicationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApplicationsPager: + r"""Lists Applications in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_applications(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListApplicationsRequest, dict]): + The request object. Message for requesting list of + Applications. + parent (str): + Required. Parent value for + ListApplicationsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListApplicationsPager: + Message for response to listing + Applications. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListApplicationsRequest): + request = platform.ListApplicationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_applications] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListApplicationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_application(self, + request: Optional[Union[platform.GetApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Application: + r"""Gets details of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = client.get_application(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetApplicationRequest, dict]): + The request object. Message for getting a Application. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Application: + Message describing Application object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetApplicationRequest): + request = platform.GetApplicationRequest(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_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_application(self, + request: Optional[Union[platform.CreateApplicationRequest, dict]] = None, + *, + parent: Optional[str] = None, + application: Optional[platform.Application] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Application in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateApplicationRequest, dict]): + The request object. Message for creating a Application. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application (google.cloud.visionai_v1alpha1.types.Application): + Required. The resource being created. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, application]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationRequest): + request = platform.CreateApplicationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if application is not None: + request.application = application + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_application(self, + request: Optional[Union[platform.UpdateApplicationRequest, dict]] = None, + *, + application: Optional[platform.Application] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateApplicationRequest, dict]): + The request object. Message for updating an Application. + application (google.cloud.visionai_v1alpha1.types.Application): + Required. The resource being updated. + This corresponds to the ``application`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Application resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Application` + Message describing Application object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([application, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationRequest): + request = platform.UpdateApplicationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if application is not None: + request.application = application + 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_application] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("application.name", request.application.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Application, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_application(self, + request: Optional[Union[platform.DeleteApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteApplicationRequest, dict]): + The request object. Message for deleting an Application. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationRequest): + request = platform.DeleteApplicationRequest(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_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def deploy_application(self, + request: Optional[Union[platform.DeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_deploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeployApplicationRequest, dict]): + The request object. Message for deploying an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.DeployApplicationResponse` RPC Request Messages. + Message for DeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeployApplicationRequest): + request = platform.DeployApplicationRequest(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.deploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.DeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def undeploy_application(self, + request: Optional[Union[platform.UndeployApplicationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Undeploys a single Application. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_undeploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UndeployApplicationRequest, dict]): + The request object. Message for undeploying an + Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.UndeployApplicationResponse` + Message for UndeployApplication Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UndeployApplicationRequest): + request = platform.UndeployApplicationRequest(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.undeploy_application] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.UndeployApplicationResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def add_application_stream_input(self, + request: Optional[Union[platform.AddApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_add_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.AddApplicationStreamInputRequest, dict]): + The request object. Message for adding stream input to an + Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.AddApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.AddApplicationStreamInputRequest): + request = platform.AddApplicationStreamInputRequest(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.add_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.AddApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def remove_application_stream_input(self, + request: Optional[Union[platform.RemoveApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.RemoveApplicationStreamInputRequest, dict]): + The request object. Message for removing stream input + from an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.RemoveApplicationStreamInputResponse` + Message for RemoveApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.RemoveApplicationStreamInputRequest): + request = platform.RemoveApplicationStreamInputRequest(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.remove_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.RemoveApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_application_stream_input(self, + request: Optional[Union[platform.UpdateApplicationStreamInputRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateApplicationStreamInputRequest, dict]): + The request object. Message for updating stream input to + an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.UpdateApplicationStreamInputResponse` + Message for AddApplicationStreamInput Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationStreamInputRequest): + request = platform.UpdateApplicationStreamInputRequest(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.update_application_stream_input] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.UpdateApplicationStreamInputResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_instances(self, + request: Optional[Union[platform.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstancesPager: + r"""Lists Instances in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListInstancesRequest, dict]): + The request object. Message for requesting list of + Instances. + parent (str): + Required. Parent value for + ListInstancesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListInstancesPager: + Message for response to listing + Instances. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListInstancesRequest): + request = platform.ListInstancesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListInstancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_instance(self, + request: Optional[Union[platform.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_instance(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetInstanceRequest, dict]): + The request object. Message for getting a Instance. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Instance: + Message describing Instance object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetInstanceRequest): + request = platform.GetInstanceRequest(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_instance] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_application_instances(self, + request: Optional[Union[platform.CreateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + application_instances = visionai_v1alpha1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateApplicationInstancesRequest, dict]): + The request object. Message for adding stream input to an + Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.CreateApplicationInstancesResponse` + Message for CreateApplicationInstance Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateApplicationInstancesRequest): + request = platform.CreateApplicationInstancesRequest(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.create_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.CreateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_application_instances(self, + request: Optional[Union[platform.DeleteApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteApplicationInstancesRequest, dict]): + The request object. Message for removing stream input + from an Application. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Instance` + Message describing Instance object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteApplicationInstancesRequest): + request = platform.DeleteApplicationInstancesRequest(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_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Instance, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_application_instances(self, + request: Optional[Union[platform.UpdateApplicationInstancesRequest, dict]] = None, + *, + name: Optional[str] = None, + application_instances: Optional[MutableSequence[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest, dict]): + The request object. Message for updating an + ApplicationInstance. + name (str): + Required. the name of the application + to retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + application_instances (MutableSequence[google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]): + + This corresponds to the ``application_instances`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesResponse` + Message for UpdateApplicationInstances Response. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, application_instances]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateApplicationInstancesRequest): + request = platform.UpdateApplicationInstancesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if application_instances is not None: + request.application_instances = application_instances + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_application_instances] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.UpdateApplicationInstancesResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_drafts(self, + request: Optional[Union[platform.ListDraftsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDraftsPager: + r"""Lists Drafts in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_drafts(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListDraftsRequest, dict]): + The request object. Message for requesting list of + Drafts. + parent (str): + Required. Parent value for + ListDraftsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListDraftsPager: + Message for response to listing + Drafts. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListDraftsRequest): + request = platform.ListDraftsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_drafts] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListDraftsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_draft(self, + request: Optional[Union[platform.GetDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Draft: + r"""Gets details of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = client.get_draft(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetDraftRequest, dict]): + The request object. Message for getting a Draft. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Draft: + Message describing Draft object + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetDraftRequest): + request = platform.GetDraftRequest(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_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_draft(self, + request: Optional[Union[platform.CreateDraftRequest, dict]] = None, + *, + parent: Optional[str] = None, + draft: Optional[platform.Draft] = None, + draft_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Draft in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateDraftRequest, dict]): + The request object. Message for creating a Draft. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft (google.cloud.visionai_v1alpha1.types.Draft): + Required. The resource being created. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + draft_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``draft_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Draft` + Message describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, draft, draft_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateDraftRequest): + request = platform.CreateDraftRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if draft is not None: + request.draft = draft + if draft_id is not None: + request.draft_id = draft_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_draft(self, + request: Optional[Union[platform.UpdateDraftRequest, dict]] = None, + *, + draft: Optional[platform.Draft] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateDraftRequest, dict]): + The request object. Message for updating an Draft. + draft (google.cloud.visionai_v1alpha1.types.Draft): + Required. The resource being updated. + This corresponds to the ``draft`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Draft` + Message describing Draft object + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([draft, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateDraftRequest): + request = platform.UpdateDraftRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if draft is not None: + request.draft = draft + 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_draft] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("draft.name", request.draft.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Draft, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_draft(self, + request: Optional[Union[platform.DeleteDraftRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Draft. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteDraftRequest, dict]): + The request object. Message for deleting an Draft. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteDraftRequest): + request = platform.DeleteDraftRequest(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_draft] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_processors(self, + request: Optional[Union[platform.ListProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProcessorsPager: + r"""Lists Processors in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListProcessorsRequest, dict]): + The request object. Message for requesting list of + Processors. + parent (str): + Required. Parent value for + ListProcessorsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListProcessorsPager: + Message for response to listing + Processors. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListProcessorsRequest): + request = platform.ListProcessorsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListProcessorsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_prebuilt_processors(self, + request: Optional[Union[platform.ListPrebuiltProcessorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.ListPrebuiltProcessorsResponse: + r"""ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsRequest, dict]): + The request object. Request Message for listing Prebuilt + Processors. + parent (str): + Required. Parent path. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsResponse: + Response Message for listing Prebuilt + Processors. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.ListPrebuiltProcessorsRequest): + request = platform.ListPrebuiltProcessorsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_prebuilt_processors] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_processor(self, + request: Optional[Union[platform.GetProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> platform.Processor: + r"""Gets details of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetProcessorRequest, dict]): + The request object. Message for getting a Processor. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Processor: + Message describing Processor object. + Next ID: 18 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.GetProcessorRequest): + request = platform.GetProcessorRequest(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_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_processor(self, + request: Optional[Union[platform.CreateProcessorRequest, dict]] = None, + *, + parent: Optional[str] = None, + processor: Optional[platform.Processor] = None, + processor_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Processor in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateProcessorRequest, dict]): + The request object. Message for creating a Processor. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor (google.cloud.visionai_v1alpha1.types.Processor): + Required. The resource being created. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``processor_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Processor` Message describing Processor object. + Next ID: 18 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, processor, processor_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.CreateProcessorRequest): + request = platform.CreateProcessorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor is not None: + request.processor = processor + if processor_id is not None: + request.processor_id = processor_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_processor(self, + request: Optional[Union[platform.UpdateProcessorRequest, dict]] = None, + *, + processor: Optional[platform.Processor] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateProcessorRequest, dict]): + The request object. Message for updating a Processor. + processor (google.cloud.visionai_v1alpha1.types.Processor): + Required. The resource being updated. + This corresponds to the ``processor`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Processor resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Processor` Message describing Processor object. + Next ID: 18 + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([processor, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.UpdateProcessorRequest): + request = platform.UpdateProcessorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if processor is not None: + request.processor = processor + 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_processor] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("processor.name", request.processor.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + platform.Processor, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_processor(self, + request: Optional[Union[platform.DeleteProcessorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Processor. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteProcessorRequest, dict]): + The request object. Message for deleting a Processor. + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, platform.DeleteProcessorRequest): + request = platform.DeleteProcessorRequest(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_processor] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AppPlatformClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AppPlatformClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/pagers.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/pagers.py new file mode 100644 index 000000000000..1816498c6dd2 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/pagers.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1alpha1.types import platform + + +class ListApplicationsPager: + """A pager for iterating through ``list_applications`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListApplicationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``applications`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApplications`` requests and continue to iterate + through the ``applications`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListApplicationsResponse` + 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[..., platform.ListApplicationsResponse], + request: platform.ListApplicationsRequest, + response: platform.ListApplicationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListApplicationsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListApplicationsResponse): + 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 = platform.ListApplicationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListApplicationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Application]: + for page in self.pages: + yield from page.applications + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApplicationsAsyncPager: + """A pager for iterating through ``list_applications`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListApplicationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``applications`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApplications`` requests and continue to iterate + through the ``applications`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListApplicationsResponse` + 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[platform.ListApplicationsResponse]], + request: platform.ListApplicationsRequest, + response: platform.ListApplicationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListApplicationsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListApplicationsResponse): + 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 = platform.ListApplicationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListApplicationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Application]: + async def async_generator(): + async for page in self.pages: + for response in page.applications: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListInstancesResponse` + 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[..., platform.ListInstancesResponse], + request: platform.ListInstancesRequest, + response: platform.ListInstancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListInstancesResponse): + 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 = platform.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListInstancesResponse` + 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[platform.ListInstancesResponse]], + request: platform.ListInstancesRequest, + response: platform.ListInstancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListInstancesResponse): + 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 = platform.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDraftsPager: + """A pager for iterating through ``list_drafts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListDraftsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``drafts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDrafts`` requests and continue to iterate + through the ``drafts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListDraftsResponse` + 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[..., platform.ListDraftsResponse], + request: platform.ListDraftsRequest, + response: platform.ListDraftsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListDraftsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListDraftsResponse): + 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 = platform.ListDraftsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListDraftsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Draft]: + for page in self.pages: + yield from page.drafts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDraftsAsyncPager: + """A pager for iterating through ``list_drafts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListDraftsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``drafts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDrafts`` requests and continue to iterate + through the ``drafts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListDraftsResponse` + 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[platform.ListDraftsResponse]], + request: platform.ListDraftsRequest, + response: platform.ListDraftsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListDraftsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListDraftsResponse): + 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 = platform.ListDraftsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListDraftsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Draft]: + async def async_generator(): + async for page in self.pages: + for response in page.drafts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListProcessorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListProcessorsResponse` + 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[..., platform.ListProcessorsResponse], + request: platform.ListProcessorsRequest, + response: platform.ListProcessorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListProcessorsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListProcessorsResponse): + 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 = platform.ListProcessorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[platform.ListProcessorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[platform.Processor]: + for page in self.pages: + yield from page.processors + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProcessorsAsyncPager: + """A pager for iterating through ``list_processors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListProcessorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``processors`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProcessors`` requests and continue to iterate + through the ``processors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListProcessorsResponse` + 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[platform.ListProcessorsResponse]], + request: platform.ListProcessorsRequest, + response: platform.ListProcessorsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListProcessorsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListProcessorsResponse): + 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 = platform.ListProcessorsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[platform.ListProcessorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[platform.Processor]: + async def async_generator(): + async for page in self.pages: + for response in page.processors: + 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/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/__init__.py new file mode 100644 index 000000000000..cab5e0b65301 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 AppPlatformTransport +from .grpc import AppPlatformGrpcTransport +from .grpc_asyncio import AppPlatformGrpcAsyncIOTransport +from .rest import AppPlatformRestTransport +from .rest import AppPlatformRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AppPlatformTransport]] +_transport_registry['grpc'] = AppPlatformGrpcTransport +_transport_registry['grpc_asyncio'] = AppPlatformGrpcAsyncIOTransport +_transport_registry['rest'] = AppPlatformRestTransport + +__all__ = ( + 'AppPlatformTransport', + 'AppPlatformGrpcTransport', + 'AppPlatformGrpcAsyncIOTransport', + 'AppPlatformRestTransport', + 'AppPlatformRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/base.py new file mode 100644 index 000000000000..a398721381f9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/base.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AppPlatformTransport(abc.ABC): + """Abstract transport class for AppPlatform.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_applications: gapic_v1.method.wrap_method( + self.list_applications, + default_timeout=None, + client_info=client_info, + ), + self.get_application: gapic_v1.method.wrap_method( + self.get_application, + default_timeout=None, + client_info=client_info, + ), + self.create_application: gapic_v1.method.wrap_method( + self.create_application, + default_timeout=None, + client_info=client_info, + ), + self.update_application: gapic_v1.method.wrap_method( + self.update_application, + default_timeout=None, + client_info=client_info, + ), + self.delete_application: gapic_v1.method.wrap_method( + self.delete_application, + default_timeout=None, + client_info=client_info, + ), + self.deploy_application: gapic_v1.method.wrap_method( + self.deploy_application, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_application: gapic_v1.method.wrap_method( + self.undeploy_application, + default_timeout=None, + client_info=client_info, + ), + self.add_application_stream_input: gapic_v1.method.wrap_method( + self.add_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.remove_application_stream_input: gapic_v1.method.wrap_method( + self.remove_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.update_application_stream_input: gapic_v1.method.wrap_method( + self.update_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_application_instances: gapic_v1.method.wrap_method( + self.create_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.delete_application_instances: gapic_v1.method.wrap_method( + self.delete_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.update_application_instances: gapic_v1.method.wrap_method( + self.update_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.list_drafts: gapic_v1.method.wrap_method( + self.list_drafts, + default_timeout=None, + client_info=client_info, + ), + self.get_draft: gapic_v1.method.wrap_method( + self.get_draft, + default_timeout=None, + client_info=client_info, + ), + self.create_draft: gapic_v1.method.wrap_method( + self.create_draft, + default_timeout=None, + client_info=client_info, + ), + self.update_draft: gapic_v1.method.wrap_method( + self.update_draft, + default_timeout=None, + client_info=client_info, + ), + self.delete_draft: gapic_v1.method.wrap_method( + self.delete_draft, + default_timeout=None, + client_info=client_info, + ), + self.list_processors: gapic_v1.method.wrap_method( + self.list_processors, + default_timeout=None, + client_info=client_info, + ), + self.list_prebuilt_processors: gapic_v1.method.wrap_method( + self.list_prebuilt_processors, + default_timeout=None, + client_info=client_info, + ), + self.get_processor: gapic_v1.method.wrap_method( + self.get_processor, + default_timeout=None, + client_info=client_info, + ), + self.create_processor: gapic_v1.method.wrap_method( + self.create_processor, + default_timeout=None, + client_info=client_info, + ), + self.update_processor: gapic_v1.method.wrap_method( + self.update_processor, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor: gapic_v1.method.wrap_method( + self.delete_processor, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + Union[ + platform.ListApplicationsResponse, + Awaitable[platform.ListApplicationsResponse] + ]]: + raise NotImplementedError() + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + Union[ + platform.Application, + Awaitable[platform.Application] + ]]: + raise NotImplementedError() + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + Union[ + platform.ListInstancesResponse, + Awaitable[platform.ListInstancesResponse] + ]]: + raise NotImplementedError() + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + Union[ + platform.Instance, + Awaitable[platform.Instance] + ]]: + raise NotImplementedError() + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + Union[ + platform.ListDraftsResponse, + Awaitable[platform.ListDraftsResponse] + ]]: + raise NotImplementedError() + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + Union[ + platform.Draft, + Awaitable[platform.Draft] + ]]: + raise NotImplementedError() + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + Union[ + platform.ListProcessorsResponse, + Awaitable[platform.ListProcessorsResponse] + ]]: + raise NotImplementedError() + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + Union[ + platform.ListPrebuiltProcessorsResponse, + Awaitable[platform.ListPrebuiltProcessorsResponse] + ]]: + raise NotImplementedError() + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + Union[ + platform.Processor, + Awaitable[platform.Processor] + ]]: + raise NotImplementedError() + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AppPlatformTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/grpc.py new file mode 100644 index 000000000000..c791370338b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/grpc.py @@ -0,0 +1,1151 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AppPlatformTransport, DEFAULT_CLIENT_INFO + + +class AppPlatformGrpcTransport(AppPlatformTransport): + """gRPC backend transport for AppPlatform. + + Service describing handlers for resources + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + platform.ListApplicationsResponse]: + r"""Return a callable for the list applications method over gRPC. + + Lists Applications in a given project and location. + + Returns: + Callable[[~.ListApplicationsRequest], + ~.ListApplicationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_applications' not in self._stubs: + self._stubs['list_applications'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListApplications', + request_serializer=platform.ListApplicationsRequest.serialize, + response_deserializer=platform.ListApplicationsResponse.deserialize, + ) + return self._stubs['list_applications'] + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + platform.Application]: + r"""Return a callable for the get application method over gRPC. + + Gets details of a single Application. + + Returns: + Callable[[~.GetApplicationRequest], + ~.Application]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_application' not in self._stubs: + self._stubs['get_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetApplication', + request_serializer=platform.GetApplicationRequest.serialize, + response_deserializer=platform.Application.deserialize, + ) + return self._stubs['get_application'] + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create application method over gRPC. + + Creates a new Application in a given project and + location. + + Returns: + Callable[[~.CreateApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application' not in self._stubs: + self._stubs['create_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateApplication', + request_serializer=platform.CreateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application'] + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update application method over gRPC. + + Updates the parameters of a single Application. + + Returns: + Callable[[~.UpdateApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application' not in self._stubs: + self._stubs['update_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateApplication', + request_serializer=platform.UpdateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application'] + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete application method over gRPC. + + Deletes a single Application. + + Returns: + Callable[[~.DeleteApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application' not in self._stubs: + self._stubs['delete_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteApplication', + request_serializer=platform.DeleteApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application'] + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the deploy application method over gRPC. + + Deploys a single Application. + + Returns: + Callable[[~.DeployApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_application' not in self._stubs: + self._stubs['deploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeployApplication', + request_serializer=platform.DeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_application'] + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the undeploy application method over gRPC. + + Undeploys a single Application. + + Returns: + Callable[[~.UndeployApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undeploy_application' not in self._stubs: + self._stubs['undeploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UndeployApplication', + request_serializer=platform.UndeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_application'] + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + operations_pb2.Operation]: + r"""Return a callable for the add application stream input method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.AddApplicationStreamInputRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_application_stream_input' not in self._stubs: + self._stubs['add_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/AddApplicationStreamInput', + request_serializer=platform.AddApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_application_stream_input'] + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove application stream + input method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.RemoveApplicationStreamInputRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_application_stream_input' not in self._stubs: + self._stubs['remove_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/RemoveApplicationStreamInput', + request_serializer=platform.RemoveApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_application_stream_input'] + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + operations_pb2.Operation]: + r"""Return a callable for the update application stream + input method over gRPC. + + Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + Returns: + Callable[[~.UpdateApplicationStreamInputRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_stream_input' not in self._stubs: + self._stubs['update_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateApplicationStreamInput', + request_serializer=platform.UpdateApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_stream_input'] + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + platform.ListInstancesResponse]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListInstances', + request_serializer=platform.ListInstancesRequest.serialize, + response_deserializer=platform.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + platform.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetInstance', + request_serializer=platform.GetInstanceRequest.serialize, + response_deserializer=platform.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the create application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.CreateApplicationInstancesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application_instances' not in self._stubs: + self._stubs['create_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateApplicationInstances', + request_serializer=platform.CreateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application_instances'] + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete application instances method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.DeleteApplicationInstancesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application_instances' not in self._stubs: + self._stubs['delete_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteApplicationInstances', + request_serializer=platform.DeleteApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application_instances'] + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the update application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.UpdateApplicationInstancesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_instances' not in self._stubs: + self._stubs['update_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateApplicationInstances', + request_serializer=platform.UpdateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_instances'] + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + platform.ListDraftsResponse]: + r"""Return a callable for the list drafts method over gRPC. + + Lists Drafts in a given project and location. + + Returns: + Callable[[~.ListDraftsRequest], + ~.ListDraftsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_drafts' not in self._stubs: + self._stubs['list_drafts'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListDrafts', + request_serializer=platform.ListDraftsRequest.serialize, + response_deserializer=platform.ListDraftsResponse.deserialize, + ) + return self._stubs['list_drafts'] + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + platform.Draft]: + r"""Return a callable for the get draft method over gRPC. + + Gets details of a single Draft. + + Returns: + Callable[[~.GetDraftRequest], + ~.Draft]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_draft' not in self._stubs: + self._stubs['get_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetDraft', + request_serializer=platform.GetDraftRequest.serialize, + response_deserializer=platform.Draft.deserialize, + ) + return self._stubs['get_draft'] + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + operations_pb2.Operation]: + r"""Return a callable for the create draft method over gRPC. + + Creates a new Draft in a given project and location. + + Returns: + Callable[[~.CreateDraftRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_draft' not in self._stubs: + self._stubs['create_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateDraft', + request_serializer=platform.CreateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_draft'] + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + operations_pb2.Operation]: + r"""Return a callable for the update draft method over gRPC. + + Updates the parameters of a single Draft. + + Returns: + Callable[[~.UpdateDraftRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_draft' not in self._stubs: + self._stubs['update_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateDraft', + request_serializer=platform.UpdateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_draft'] + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete draft method over gRPC. + + Deletes a single Draft. + + Returns: + Callable[[~.DeleteDraftRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_draft' not in self._stubs: + self._stubs['delete_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteDraft', + request_serializer=platform.DeleteDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_draft'] + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + platform.ListProcessorsResponse]: + r"""Return a callable for the list processors method over gRPC. + + Lists Processors in a given project and location. + + Returns: + Callable[[~.ListProcessorsRequest], + ~.ListProcessorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListProcessors', + request_serializer=platform.ListProcessorsRequest.serialize, + response_deserializer=platform.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + platform.ListPrebuiltProcessorsResponse]: + r"""Return a callable for the list prebuilt processors method over gRPC. + + ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + Returns: + Callable[[~.ListPrebuiltProcessorsRequest], + ~.ListPrebuiltProcessorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prebuilt_processors' not in self._stubs: + self._stubs['list_prebuilt_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListPrebuiltProcessors', + request_serializer=platform.ListPrebuiltProcessorsRequest.serialize, + response_deserializer=platform.ListPrebuiltProcessorsResponse.deserialize, + ) + return self._stubs['list_prebuilt_processors'] + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + platform.Processor]: + r"""Return a callable for the get processor method over gRPC. + + Gets details of a single Processor. + + Returns: + Callable[[~.GetProcessorRequest], + ~.Processor]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetProcessor', + request_serializer=platform.GetProcessorRequest.serialize, + response_deserializer=platform.Processor.deserialize, + ) + return self._stubs['get_processor'] + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the create processor method over gRPC. + + Creates a new Processor in a given project and + location. + + Returns: + Callable[[~.CreateProcessorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateProcessor', + request_serializer=platform.CreateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_processor'] + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the update processor method over gRPC. + + Updates the parameters of a single Processor. + + Returns: + Callable[[~.UpdateProcessorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_processor' not in self._stubs: + self._stubs['update_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateProcessor', + request_serializer=platform.UpdateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_processor'] + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes a single Processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteProcessor', + request_serializer=platform.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AppPlatformGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/grpc_asyncio.py new file mode 100644 index 000000000000..639c6456d9d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/grpc_asyncio.py @@ -0,0 +1,1286 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AppPlatformTransport, DEFAULT_CLIENT_INFO +from .grpc import AppPlatformGrpcTransport + + +class AppPlatformGrpcAsyncIOTransport(AppPlatformTransport): + """gRPC AsyncIO backend transport for AppPlatform. + + Service describing handlers for resources + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + Awaitable[platform.ListApplicationsResponse]]: + r"""Return a callable for the list applications method over gRPC. + + Lists Applications in a given project and location. + + Returns: + Callable[[~.ListApplicationsRequest], + Awaitable[~.ListApplicationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_applications' not in self._stubs: + self._stubs['list_applications'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListApplications', + request_serializer=platform.ListApplicationsRequest.serialize, + response_deserializer=platform.ListApplicationsResponse.deserialize, + ) + return self._stubs['list_applications'] + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + Awaitable[platform.Application]]: + r"""Return a callable for the get application method over gRPC. + + Gets details of a single Application. + + Returns: + Callable[[~.GetApplicationRequest], + Awaitable[~.Application]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_application' not in self._stubs: + self._stubs['get_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetApplication', + request_serializer=platform.GetApplicationRequest.serialize, + response_deserializer=platform.Application.deserialize, + ) + return self._stubs['get_application'] + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create application method over gRPC. + + Creates a new Application in a given project and + location. + + Returns: + Callable[[~.CreateApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application' not in self._stubs: + self._stubs['create_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateApplication', + request_serializer=platform.CreateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application'] + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update application method over gRPC. + + Updates the parameters of a single Application. + + Returns: + Callable[[~.UpdateApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application' not in self._stubs: + self._stubs['update_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateApplication', + request_serializer=platform.UpdateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application'] + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete application method over gRPC. + + Deletes a single Application. + + Returns: + Callable[[~.DeleteApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application' not in self._stubs: + self._stubs['delete_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteApplication', + request_serializer=platform.DeleteApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application'] + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the deploy application method over gRPC. + + Deploys a single Application. + + Returns: + Callable[[~.DeployApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_application' not in self._stubs: + self._stubs['deploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeployApplication', + request_serializer=platform.DeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_application'] + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the undeploy application method over gRPC. + + Undeploys a single Application. + + Returns: + Callable[[~.UndeployApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undeploy_application' not in self._stubs: + self._stubs['undeploy_application'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UndeployApplication', + request_serializer=platform.UndeployApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undeploy_application'] + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add application stream input method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.AddApplicationStreamInputRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'add_application_stream_input' not in self._stubs: + self._stubs['add_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/AddApplicationStreamInput', + request_serializer=platform.AddApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_application_stream_input'] + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove application stream + input method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.RemoveApplicationStreamInputRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'remove_application_stream_input' not in self._stubs: + self._stubs['remove_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/RemoveApplicationStreamInput', + request_serializer=platform.RemoveApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_application_stream_input'] + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update application stream + input method over gRPC. + + Update target stream input to the Application, if the + Application is deployed, the corresponding instance based will + be deployed. For CreateOrUpdate behavior, set allow_missing to + true. + + Returns: + Callable[[~.UpdateApplicationStreamInputRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_stream_input' not in self._stubs: + self._stubs['update_application_stream_input'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateApplicationStreamInput', + request_serializer=platform.UpdateApplicationStreamInputRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_stream_input'] + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + Awaitable[platform.ListInstancesResponse]]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListInstances', + request_serializer=platform.ListInstancesRequest.serialize, + response_deserializer=platform.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + Awaitable[platform.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetInstance', + request_serializer=platform.GetInstanceRequest.serialize, + response_deserializer=platform.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.CreateApplicationInstancesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application_instances' not in self._stubs: + self._stubs['create_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateApplicationInstances', + request_serializer=platform.CreateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application_instances'] + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete application instances method over gRPC. + + Remove target stream input to the Application, if the + Application is deployed, the corresponding instance + based will be deleted. If the stream is not in the + Application, the RPC will fail. + + Returns: + Callable[[~.DeleteApplicationInstancesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_application_instances' not in self._stubs: + self._stubs['delete_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteApplicationInstances', + request_serializer=platform.DeleteApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_application_instances'] + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update application instances method over gRPC. + + Adds target stream input to the Application. + If the Application is deployed, the corresponding new + Application instance will be created. If the stream has + already been in the Application, the RPC will fail. + + Returns: + Callable[[~.UpdateApplicationInstancesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application_instances' not in self._stubs: + self._stubs['update_application_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateApplicationInstances', + request_serializer=platform.UpdateApplicationInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application_instances'] + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + Awaitable[platform.ListDraftsResponse]]: + r"""Return a callable for the list drafts method over gRPC. + + Lists Drafts in a given project and location. + + Returns: + Callable[[~.ListDraftsRequest], + Awaitable[~.ListDraftsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_drafts' not in self._stubs: + self._stubs['list_drafts'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListDrafts', + request_serializer=platform.ListDraftsRequest.serialize, + response_deserializer=platform.ListDraftsResponse.deserialize, + ) + return self._stubs['list_drafts'] + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + Awaitable[platform.Draft]]: + r"""Return a callable for the get draft method over gRPC. + + Gets details of a single Draft. + + Returns: + Callable[[~.GetDraftRequest], + Awaitable[~.Draft]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_draft' not in self._stubs: + self._stubs['get_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetDraft', + request_serializer=platform.GetDraftRequest.serialize, + response_deserializer=platform.Draft.deserialize, + ) + return self._stubs['get_draft'] + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create draft method over gRPC. + + Creates a new Draft in a given project and location. + + Returns: + Callable[[~.CreateDraftRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_draft' not in self._stubs: + self._stubs['create_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateDraft', + request_serializer=platform.CreateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_draft'] + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update draft method over gRPC. + + Updates the parameters of a single Draft. + + Returns: + Callable[[~.UpdateDraftRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_draft' not in self._stubs: + self._stubs['update_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateDraft', + request_serializer=platform.UpdateDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_draft'] + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete draft method over gRPC. + + Deletes a single Draft. + + Returns: + Callable[[~.DeleteDraftRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_draft' not in self._stubs: + self._stubs['delete_draft'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteDraft', + request_serializer=platform.DeleteDraftRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_draft'] + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + Awaitable[platform.ListProcessorsResponse]]: + r"""Return a callable for the list processors method over gRPC. + + Lists Processors in a given project and location. + + Returns: + Callable[[~.ListProcessorsRequest], + Awaitable[~.ListProcessorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processors' not in self._stubs: + self._stubs['list_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListProcessors', + request_serializer=platform.ListProcessorsRequest.serialize, + response_deserializer=platform.ListProcessorsResponse.deserialize, + ) + return self._stubs['list_processors'] + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + Awaitable[platform.ListPrebuiltProcessorsResponse]]: + r"""Return a callable for the list prebuilt processors method over gRPC. + + ListPrebuiltProcessors is a custom pass-through verb + that Lists Prebuilt Processors. + + Returns: + Callable[[~.ListPrebuiltProcessorsRequest], + Awaitable[~.ListPrebuiltProcessorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prebuilt_processors' not in self._stubs: + self._stubs['list_prebuilt_processors'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/ListPrebuiltProcessors', + request_serializer=platform.ListPrebuiltProcessorsRequest.serialize, + response_deserializer=platform.ListPrebuiltProcessorsResponse.deserialize, + ) + return self._stubs['list_prebuilt_processors'] + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + Awaitable[platform.Processor]]: + r"""Return a callable for the get processor method over gRPC. + + Gets details of a single Processor. + + Returns: + Callable[[~.GetProcessorRequest], + Awaitable[~.Processor]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_processor' not in self._stubs: + self._stubs['get_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/GetProcessor', + request_serializer=platform.GetProcessorRequest.serialize, + response_deserializer=platform.Processor.deserialize, + ) + return self._stubs['get_processor'] + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create processor method over gRPC. + + Creates a new Processor in a given project and + location. + + Returns: + Callable[[~.CreateProcessorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_processor' not in self._stubs: + self._stubs['create_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/CreateProcessor', + request_serializer=platform.CreateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_processor'] + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update processor method over gRPC. + + Updates the parameters of a single Processor. + + Returns: + Callable[[~.UpdateProcessorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_processor' not in self._stubs: + self._stubs['update_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/UpdateProcessor', + request_serializer=platform.UpdateProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_processor'] + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete processor method over gRPC. + + Deletes a single Processor. + + Returns: + Callable[[~.DeleteProcessorRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_processor' not in self._stubs: + self._stubs['delete_processor'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.AppPlatform/DeleteProcessor', + request_serializer=platform.DeleteProcessorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_processor'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_applications: gapic_v1.method_async.wrap_method( + self.list_applications, + default_timeout=None, + client_info=client_info, + ), + self.get_application: gapic_v1.method_async.wrap_method( + self.get_application, + default_timeout=None, + client_info=client_info, + ), + self.create_application: gapic_v1.method_async.wrap_method( + self.create_application, + default_timeout=None, + client_info=client_info, + ), + self.update_application: gapic_v1.method_async.wrap_method( + self.update_application, + default_timeout=None, + client_info=client_info, + ), + self.delete_application: gapic_v1.method_async.wrap_method( + self.delete_application, + default_timeout=None, + client_info=client_info, + ), + self.deploy_application: gapic_v1.method_async.wrap_method( + self.deploy_application, + default_timeout=None, + client_info=client_info, + ), + self.undeploy_application: gapic_v1.method_async.wrap_method( + self.undeploy_application, + default_timeout=None, + client_info=client_info, + ), + self.add_application_stream_input: gapic_v1.method_async.wrap_method( + self.add_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.remove_application_stream_input: gapic_v1.method_async.wrap_method( + self.remove_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.update_application_stream_input: gapic_v1.method_async.wrap_method( + self.update_application_stream_input, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method_async.wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method_async.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_application_instances: gapic_v1.method_async.wrap_method( + self.create_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.delete_application_instances: gapic_v1.method_async.wrap_method( + self.delete_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.update_application_instances: gapic_v1.method_async.wrap_method( + self.update_application_instances, + default_timeout=None, + client_info=client_info, + ), + self.list_drafts: gapic_v1.method_async.wrap_method( + self.list_drafts, + default_timeout=None, + client_info=client_info, + ), + self.get_draft: gapic_v1.method_async.wrap_method( + self.get_draft, + default_timeout=None, + client_info=client_info, + ), + self.create_draft: gapic_v1.method_async.wrap_method( + self.create_draft, + default_timeout=None, + client_info=client_info, + ), + self.update_draft: gapic_v1.method_async.wrap_method( + self.update_draft, + default_timeout=None, + client_info=client_info, + ), + self.delete_draft: gapic_v1.method_async.wrap_method( + self.delete_draft, + default_timeout=None, + client_info=client_info, + ), + self.list_processors: gapic_v1.method_async.wrap_method( + self.list_processors, + default_timeout=None, + client_info=client_info, + ), + self.list_prebuilt_processors: gapic_v1.method_async.wrap_method( + self.list_prebuilt_processors, + default_timeout=None, + client_info=client_info, + ), + self.get_processor: gapic_v1.method_async.wrap_method( + self.get_processor, + default_timeout=None, + client_info=client_info, + ), + self.create_processor: gapic_v1.method_async.wrap_method( + self.create_processor, + default_timeout=None, + client_info=client_info, + ), + self.update_processor: gapic_v1.method_async.wrap_method( + self.update_processor, + default_timeout=None, + client_info=client_info, + ), + self.delete_processor: gapic_v1.method_async.wrap_method( + self.delete_processor, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'AppPlatformGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/rest.py new file mode 100644 index 000000000000..9d8befd40816 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/app_platform/transports/rest.py @@ -0,0 +1,4098 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1alpha1.types import platform +from google.longrunning import operations_pb2 # type: ignore + +from .base import AppPlatformTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class AppPlatformRestInterceptor: + """Interceptor for AppPlatform. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AppPlatformRestTransport. + + .. code-block:: python + class MyCustomAppPlatformInterceptor(AppPlatformRestInterceptor): + def pre_add_application_stream_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_application_stream_input(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_application_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_application_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_application_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_application_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_deploy_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_deploy_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_applications(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_applications(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_drafts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_drafts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_prebuilt_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_prebuilt_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_application_stream_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_application_stream_input(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undeploy_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undeploy_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_application(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_application(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_application_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_application_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_application_stream_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_application_stream_input(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_draft(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_draft(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_processor(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AppPlatformRestTransport(interceptor=MyCustomAppPlatformInterceptor()) + client = AppPlatformClient(transport=transport) + + + """ + def pre_add_application_stream_input(self, request: platform.AddApplicationStreamInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.AddApplicationStreamInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for add_application_stream_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_add_application_stream_input(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for add_application_stream_input + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_application(self, request: platform.CreateApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_application_instances(self, request: platform.CreateApplicationInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateApplicationInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_application_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_application_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_application_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_draft(self, request: platform.CreateDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_draft(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_create_processor(self, request: platform.CreateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.CreateProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_create_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_application(self, request: platform.DeleteApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_application_instances(self, request: platform.DeleteApplicationInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteApplicationInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_application_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_application_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_application_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_draft(self, request: platform.DeleteDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_draft(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_processor(self, request: platform.DeleteProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeleteProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_deploy_application(self, request: platform.DeployApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.DeployApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for deploy_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_deploy_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for deploy_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_application(self, request: platform.GetApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_application(self, response: platform.Application) -> platform.Application: + """Post-rpc interceptor for get_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_draft(self, request: platform.GetDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_draft(self, response: platform.Draft) -> platform.Draft: + """Post-rpc interceptor for get_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_instance(self, request: platform.GetInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_instance(self, response: platform.Instance) -> platform.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_processor(self, request: platform.GetProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.GetProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_processor(self, response: platform.Processor) -> platform.Processor: + """Post-rpc interceptor for get_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_applications(self, request: platform.ListApplicationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListApplicationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_applications + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_applications(self, response: platform.ListApplicationsResponse) -> platform.ListApplicationsResponse: + """Post-rpc interceptor for list_applications + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_drafts(self, request: platform.ListDraftsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListDraftsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_drafts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_drafts(self, response: platform.ListDraftsResponse) -> platform.ListDraftsResponse: + """Post-rpc interceptor for list_drafts + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_instances(self, request: platform.ListInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_instances(self, response: platform.ListInstancesResponse) -> platform.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_prebuilt_processors(self, request: platform.ListPrebuiltProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListPrebuiltProcessorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_prebuilt_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_prebuilt_processors(self, response: platform.ListPrebuiltProcessorsResponse) -> platform.ListPrebuiltProcessorsResponse: + """Post-rpc interceptor for list_prebuilt_processors + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_processors(self, request: platform.ListProcessorsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.ListProcessorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_processors(self, response: platform.ListProcessorsResponse) -> platform.ListProcessorsResponse: + """Post-rpc interceptor for list_processors + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_remove_application_stream_input(self, request: platform.RemoveApplicationStreamInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.RemoveApplicationStreamInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for remove_application_stream_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_remove_application_stream_input(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for remove_application_stream_input + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_undeploy_application(self, request: platform.UndeployApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UndeployApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undeploy_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_undeploy_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for undeploy_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_application(self, request: platform.UpdateApplicationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateApplicationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_application + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_application(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_application + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_application_instances(self, request: platform.UpdateApplicationInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateApplicationInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_application_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_application_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_application_instances + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_application_stream_input(self, request: platform.UpdateApplicationStreamInputRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateApplicationStreamInputRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_application_stream_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_application_stream_input(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_application_stream_input + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_draft(self, request: platform.UpdateDraftRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateDraftRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_draft + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_draft(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_draft + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_update_processor(self, request: platform.UpdateProcessorRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[platform.UpdateProcessorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_update_processor(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_processor + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AppPlatform server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the AppPlatform server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AppPlatformRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AppPlatformRestInterceptor + + +class AppPlatformRestTransport(AppPlatformTransport): + """REST backend transport for AppPlatform. + + Service describing handlers for resources + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[AppPlatformRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AppPlatformRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _AddApplicationStreamInput(AppPlatformRestStub): + def __hash__(self): + return hash("AddApplicationStreamInput") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.AddApplicationStreamInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the add application stream + input method over HTTP. + + Args: + request (~.platform.AddApplicationStreamInputRequest): + The request object. Message for adding stream input to an + Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:addStreamInput', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_add_application_stream_input(request, metadata) + pb_request = platform.AddApplicationStreamInputRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_add_application_stream_input(resp) + return resp + + class _CreateApplication(AppPlatformRestStub): + def __hash__(self): + return hash("CreateApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "applicationId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create application method over HTTP. + + Args: + request (~.platform.CreateApplicationRequest): + The request object. Message for creating a Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/applications', + 'body': 'application', + }, + ] + request, metadata = self._interceptor.pre_create_application(request, metadata) + pb_request = platform.CreateApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_application(resp) + return resp + + class _CreateApplicationInstances(AppPlatformRestStub): + def __hash__(self): + return hash("CreateApplicationInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateApplicationInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create application + instances method over HTTP. + + Args: + request (~.platform.CreateApplicationInstancesRequest): + The request object. Message for adding stream input to an + Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:createApplicationInstances', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_create_application_instances(request, metadata) + pb_request = platform.CreateApplicationInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_application_instances(resp) + return resp + + class _CreateDraft(AppPlatformRestStub): + def __hash__(self): + return hash("CreateDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "draftId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create draft method over HTTP. + + Args: + request (~.platform.CreateDraftRequest): + The request object. Message for creating a Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/applications/*}/drafts', + 'body': 'draft', + }, + ] + request, metadata = self._interceptor.pre_create_draft(request, metadata) + pb_request = platform.CreateDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_draft(resp) + return resp + + class _CreateProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("CreateProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "processorId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.CreateProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create processor method over HTTP. + + Args: + request (~.platform.CreateProcessorRequest): + The request object. Message for creating a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/processors', + 'body': 'processor', + }, + ] + request, metadata = self._interceptor.pre_create_processor(request, metadata) + pb_request = platform.CreateProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_processor(resp) + return resp + + class _DeleteApplication(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete application method over HTTP. + + Args: + request (~.platform.DeleteApplicationRequest): + The request object. Message for deleting an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_application(request, metadata) + pb_request = platform.DeleteApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_application(resp) + return resp + + class _DeleteApplicationInstances(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteApplicationInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteApplicationInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete application + instances method over HTTP. + + Args: + request (~.platform.DeleteApplicationInstancesRequest): + The request object. Message for removing stream input + from an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:deleteApplicationInstances', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_delete_application_instances(request, metadata) + pb_request = platform.DeleteApplicationInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_application_instances(resp) + return resp + + class _DeleteDraft(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete draft method over HTTP. + + Args: + request (~.platform.DeleteDraftRequest): + The request object. Message for deleting an Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*/drafts/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_draft(request, metadata) + pb_request = platform.DeleteDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_draft(resp) + return resp + + class _DeleteProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("DeleteProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeleteProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete processor method over HTTP. + + Args: + request (~.platform.DeleteProcessorRequest): + The request object. Message for deleting a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_processor(request, metadata) + pb_request = platform.DeleteProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_processor(resp) + return resp + + class _DeployApplication(AppPlatformRestStub): + def __hash__(self): + return hash("DeployApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.DeployApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the deploy application method over HTTP. + + Args: + request (~.platform.DeployApplicationRequest): + The request object. Message for deploying an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:deploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_deploy_application(request, metadata) + pb_request = platform.DeployApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_deploy_application(resp) + return resp + + class _GetApplication(AppPlatformRestStub): + def __hash__(self): + return hash("GetApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Application: + r"""Call the get application method over HTTP. + + Args: + request (~.platform.GetApplicationRequest): + The request object. Message for getting a Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Application: + Message describing Application object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}', + }, + ] + request, metadata = self._interceptor.pre_get_application(request, metadata) + pb_request = platform.GetApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Application() + pb_resp = platform.Application.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_application(resp) + return resp + + class _GetDraft(AppPlatformRestStub): + def __hash__(self): + return hash("GetDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Draft: + r"""Call the get draft method over HTTP. + + Args: + request (~.platform.GetDraftRequest): + The request object. Message for getting a Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Draft: + Message describing Draft object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*/drafts/*}', + }, + ] + request, metadata = self._interceptor.pre_get_draft(request, metadata) + pb_request = platform.GetDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Draft() + pb_resp = platform.Draft.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_draft(resp) + return resp + + class _GetInstance(AppPlatformRestStub): + def __hash__(self): + return hash("GetInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.platform.GetInstanceRequest): + The request object. Message for getting a Instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Instance: + Message describing Instance object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = platform.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Instance() + pb_resp = platform.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + class _GetProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("GetProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.GetProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.Processor: + r"""Call the get processor method over HTTP. + + Args: + request (~.platform.GetProcessorRequest): + The request object. Message for getting a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.Processor: + Message describing Processor object. + Next ID: 18 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/processors/*}', + }, + ] + request, metadata = self._interceptor.pre_get_processor(request, metadata) + pb_request = platform.GetProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.Processor() + pb_resp = platform.Processor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_processor(resp) + return resp + + class _ListApplications(AppPlatformRestStub): + def __hash__(self): + return hash("ListApplications") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListApplicationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListApplicationsResponse: + r"""Call the list applications method over HTTP. + + Args: + request (~.platform.ListApplicationsRequest): + The request object. Message for requesting list of + Applications. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListApplicationsResponse: + Message for response to listing + Applications. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/applications', + }, + ] + request, metadata = self._interceptor.pre_list_applications(request, metadata) + pb_request = platform.ListApplicationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListApplicationsResponse() + pb_resp = platform.ListApplicationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_applications(resp) + return resp + + class _ListDrafts(AppPlatformRestStub): + def __hash__(self): + return hash("ListDrafts") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListDraftsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListDraftsResponse: + r"""Call the list drafts method over HTTP. + + Args: + request (~.platform.ListDraftsRequest): + The request object. Message for requesting list of + Drafts. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListDraftsResponse: + Message for response to listing + Drafts. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/applications/*}/drafts', + }, + ] + request, metadata = self._interceptor.pre_list_drafts(request, metadata) + pb_request = platform.ListDraftsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListDraftsResponse() + pb_resp = platform.ListDraftsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_drafts(resp) + return resp + + class _ListInstances(AppPlatformRestStub): + def __hash__(self): + return hash("ListInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.platform.ListInstancesRequest): + The request object. Message for requesting list of + Instances. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListInstancesResponse: + Message for response to listing + Instances. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/applications/*}/instances', + }, + ] + request, metadata = self._interceptor.pre_list_instances(request, metadata) + pb_request = platform.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListInstancesResponse() + pb_resp = platform.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_instances(resp) + return resp + + class _ListPrebuiltProcessors(AppPlatformRestStub): + def __hash__(self): + return hash("ListPrebuiltProcessors") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListPrebuiltProcessorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListPrebuiltProcessorsResponse: + r"""Call the list prebuilt processors method over HTTP. + + Args: + request (~.platform.ListPrebuiltProcessorsRequest): + The request object. Request Message for listing Prebuilt + Processors. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListPrebuiltProcessorsResponse: + Response Message for listing Prebuilt + Processors. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/processors:prebuilt', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_list_prebuilt_processors(request, metadata) + pb_request = platform.ListPrebuiltProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListPrebuiltProcessorsResponse() + pb_resp = platform.ListPrebuiltProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_prebuilt_processors(resp) + return resp + + class _ListProcessors(AppPlatformRestStub): + def __hash__(self): + return hash("ListProcessors") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.ListProcessorsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> platform.ListProcessorsResponse: + r"""Call the list processors method over HTTP. + + Args: + request (~.platform.ListProcessorsRequest): + The request object. Message for requesting list of + Processors. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.platform.ListProcessorsResponse: + Message for response to listing + Processors. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/processors', + }, + ] + request, metadata = self._interceptor.pre_list_processors(request, metadata) + pb_request = platform.ListProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = platform.ListProcessorsResponse() + pb_resp = platform.ListProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_processors(resp) + return resp + + class _RemoveApplicationStreamInput(AppPlatformRestStub): + def __hash__(self): + return hash("RemoveApplicationStreamInput") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.RemoveApplicationStreamInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the remove application stream + input method over HTTP. + + Args: + request (~.platform.RemoveApplicationStreamInputRequest): + The request object. Message for removing stream input + from an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:removeStreamInput', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_remove_application_stream_input(request, metadata) + pb_request = platform.RemoveApplicationStreamInputRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_remove_application_stream_input(resp) + return resp + + class _UndeployApplication(AppPlatformRestStub): + def __hash__(self): + return hash("UndeployApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UndeployApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the undeploy application method over HTTP. + + Args: + request (~.platform.UndeployApplicationRequest): + The request object. Message for undeploying an + Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:undeploy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_undeploy_application(request, metadata) + pb_request = platform.UndeployApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undeploy_application(resp) + return resp + + class _UpdateApplication(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateApplication") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateApplicationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update application method over HTTP. + + Args: + request (~.platform.UpdateApplicationRequest): + The request object. Message for updating an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{application.name=projects/*/locations/*/applications/*}', + 'body': 'application', + }, + ] + request, metadata = self._interceptor.pre_update_application(request, metadata) + pb_request = platform.UpdateApplicationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_application(resp) + return resp + + class _UpdateApplicationInstances(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateApplicationInstances") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateApplicationInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update application + instances method over HTTP. + + Args: + request (~.platform.UpdateApplicationInstancesRequest): + The request object. Message for updating an + ApplicationInstance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:updateApplicationInstances', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_update_application_instances(request, metadata) + pb_request = platform.UpdateApplicationInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_application_instances(resp) + return resp + + class _UpdateApplicationStreamInput(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateApplicationStreamInput") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateApplicationStreamInputRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update application stream + input method over HTTP. + + Args: + request (~.platform.UpdateApplicationStreamInputRequest): + The request object. Message for updating stream input to + an Application. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/applications/*}:updateStreamInput', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_update_application_stream_input(request, metadata) + pb_request = platform.UpdateApplicationStreamInputRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_application_stream_input(resp) + return resp + + class _UpdateDraft(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateDraft") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateDraftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update draft method over HTTP. + + Args: + request (~.platform.UpdateDraftRequest): + The request object. Message for updating an Draft. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{draft.name=projects/*/locations/*/applications/*/drafts/*}', + 'body': 'draft', + }, + ] + request, metadata = self._interceptor.pre_update_draft(request, metadata) + pb_request = platform.UpdateDraftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_draft(resp) + return resp + + class _UpdateProcessor(AppPlatformRestStub): + def __hash__(self): + return hash("UpdateProcessor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: platform.UpdateProcessorRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update processor method over HTTP. + + Args: + request (~.platform.UpdateProcessorRequest): + The request object. Message for updating a Processor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{processor.name=projects/*/locations/*/processors/*}', + 'body': 'processor', + }, + ] + request, metadata = self._interceptor.pre_update_processor(request, metadata) + pb_request = platform.UpdateProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_processor(resp) + return resp + + @property + def add_application_stream_input(self) -> Callable[ + [platform.AddApplicationStreamInputRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AddApplicationStreamInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_application(self) -> Callable[ + [platform.CreateApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_application_instances(self) -> Callable[ + [platform.CreateApplicationInstancesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApplicationInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_draft(self) -> Callable[ + [platform.CreateDraftRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_processor(self) -> Callable[ + [platform.CreateProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_application(self) -> Callable[ + [platform.DeleteApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_application_instances(self) -> Callable[ + [platform.DeleteApplicationInstancesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApplicationInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_draft(self) -> Callable[ + [platform.DeleteDraftRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_processor(self) -> Callable[ + [platform.DeleteProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def deploy_application(self) -> Callable[ + [platform.DeployApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeployApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_application(self) -> Callable[ + [platform.GetApplicationRequest], + platform.Application]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_draft(self) -> Callable[ + [platform.GetDraftRequest], + platform.Draft]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance(self) -> Callable[ + [platform.GetInstanceRequest], + platform.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_processor(self) -> Callable[ + [platform.GetProcessorRequest], + platform.Processor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_applications(self) -> Callable[ + [platform.ListApplicationsRequest], + platform.ListApplicationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApplications(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_drafts(self) -> Callable[ + [platform.ListDraftsRequest], + platform.ListDraftsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDrafts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances(self) -> Callable[ + [platform.ListInstancesRequest], + platform.ListInstancesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_prebuilt_processors(self) -> Callable[ + [platform.ListPrebuiltProcessorsRequest], + platform.ListPrebuiltProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPrebuiltProcessors(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_processors(self) -> Callable[ + [platform.ListProcessorsRequest], + platform.ListProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProcessors(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_application_stream_input(self) -> Callable[ + [platform.RemoveApplicationStreamInputRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveApplicationStreamInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def undeploy_application(self) -> Callable[ + [platform.UndeployApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeployApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_application(self) -> Callable[ + [platform.UpdateApplicationRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApplication(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_application_instances(self) -> Callable[ + [platform.UpdateApplicationInstancesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApplicationInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_application_stream_input(self) -> Callable[ + [platform.UpdateApplicationStreamInputRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApplicationStreamInput(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_draft(self) -> Callable[ + [platform.UpdateDraftRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDraft(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_processor(self) -> Callable[ + [platform.UpdateProcessorRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateProcessor(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(AppPlatformRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(AppPlatformRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(AppPlatformRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(AppPlatformRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(AppPlatformRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(AppPlatformRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AppPlatformRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/__init__.py new file mode 100644 index 000000000000..4d7712a4fda6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LiveVideoAnalyticsClient +from .async_client import LiveVideoAnalyticsAsyncClient + +__all__ = ( + 'LiveVideoAnalyticsClient', + 'LiveVideoAnalyticsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/async_client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/async_client.py new file mode 100644 index 000000000000..502a4c589f42 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/async_client.py @@ -0,0 +1,1479 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.live_video_analytics import pagers +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import lva +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LiveVideoAnalyticsGrpcAsyncIOTransport +from .client import LiveVideoAnalyticsClient + + +class LiveVideoAnalyticsAsyncClient: + """Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + """ + + _client: LiveVideoAnalyticsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LiveVideoAnalyticsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + + analysis_path = staticmethod(LiveVideoAnalyticsClient.analysis_path) + parse_analysis_path = staticmethod(LiveVideoAnalyticsClient.parse_analysis_path) + cluster_path = staticmethod(LiveVideoAnalyticsClient.cluster_path) + parse_cluster_path = staticmethod(LiveVideoAnalyticsClient.parse_cluster_path) + common_billing_account_path = staticmethod(LiveVideoAnalyticsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LiveVideoAnalyticsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LiveVideoAnalyticsClient.common_folder_path) + parse_common_folder_path = staticmethod(LiveVideoAnalyticsClient.parse_common_folder_path) + common_organization_path = staticmethod(LiveVideoAnalyticsClient.common_organization_path) + parse_common_organization_path = staticmethod(LiveVideoAnalyticsClient.parse_common_organization_path) + common_project_path = staticmethod(LiveVideoAnalyticsClient.common_project_path) + parse_common_project_path = staticmethod(LiveVideoAnalyticsClient.parse_common_project_path) + common_location_path = staticmethod(LiveVideoAnalyticsClient.common_location_path) + parse_common_location_path = staticmethod(LiveVideoAnalyticsClient.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: + LiveVideoAnalyticsAsyncClient: The constructed client. + """ + return LiveVideoAnalyticsClient.from_service_account_info.__func__(LiveVideoAnalyticsAsyncClient, 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: + LiveVideoAnalyticsAsyncClient: The constructed client. + """ + return LiveVideoAnalyticsClient.from_service_account_file.__func__(LiveVideoAnalyticsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LiveVideoAnalyticsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LiveVideoAnalyticsTransport: + """Returns the transport used by the client instance. + + Returns: + LiveVideoAnalyticsTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(LiveVideoAnalyticsClient).get_transport_class, type(LiveVideoAnalyticsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LiveVideoAnalyticsTransport, Callable[..., LiveVideoAnalyticsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the live video analytics async 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 (Optional[Union[str,LiveVideoAnalyticsTransport,Callable[..., LiveVideoAnalyticsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LiveVideoAnalyticsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = LiveVideoAnalyticsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_analyses(self, + request: Optional[Union[lva_service.ListAnalysesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnalysesAsyncPager: + r"""Lists Analyses in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_analyses(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListAnalysesRequest, dict]]): + The request object. Message for requesting list of + Analyses + parent (:class:`str`): + Required. Parent value for + ListAnalysesRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.live_video_analytics.pagers.ListAnalysesAsyncPager: + Message for response to listing + Analyses + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListAnalysesRequest): + request = lva_service.ListAnalysesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_analyses] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAnalysesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_analysis(self, + request: Optional[Union[lva_service.GetAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Analysis: + r"""Gets details of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = await client.get_analysis(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetAnalysisRequest, dict]]): + The request object. Message for getting an Analysis. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Analysis: + Message describing the Analysis + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetAnalysisRequest): + request = lva_service.GetAnalysisRequest(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._client._transport._wrapped_methods[self._client._transport.get_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_analysis(self, + request: Optional[Union[lva_service.CreateAnalysisRequest, dict]] = None, + *, + parent: Optional[str] = None, + analysis: Optional[lva_resources.Analysis] = None, + analysis_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Analysis in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateAnalysisRequest, dict]]): + The request object. Message for creating an Analysis. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis (:class:`google.cloud.visionai_v1alpha1.types.Analysis`): + Required. The resource being created. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``analysis_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Analysis` + Message describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, analysis, analysis_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateAnalysisRequest): + request = lva_service.CreateAnalysisRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if analysis is not None: + request.analysis = analysis + if analysis_id is not None: + request.analysis_id = analysis_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_analysis(self, + request: Optional[Union[lva_service.UpdateAnalysisRequest, dict]] = None, + *, + analysis: Optional[lva_resources.Analysis] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateAnalysisRequest, dict]]): + The request object. Message for updating an Analysis. + analysis (:class:`google.cloud.visionai_v1alpha1.types.Analysis`): + Required. The resource being updated. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Analysis resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Analysis` + Message describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([analysis, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateAnalysisRequest): + request = lva_service.UpdateAnalysisRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if analysis is not None: + request.analysis = analysis + 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._client._transport._wrapped_methods[self._client._transport.update_analysis] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis.name", request.analysis.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_analysis(self, + request: Optional[Union[lva_service.DeleteAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteAnalysisRequest, dict]]): + The request object. Message for deleting an Analysis. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteAnalysisRequest): + request = lva_service.DeleteAnalysisRequest(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._client._transport._wrapped_methods[self._client._transport.delete_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "LiveVideoAnalyticsAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "LiveVideoAnalyticsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/client.py new file mode 100644 index 000000000000..7fd8a9addada --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/client.py @@ -0,0 +1,1835 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.live_video_analytics import pagers +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import lva +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LiveVideoAnalyticsGrpcTransport +from .transports.grpc_asyncio import LiveVideoAnalyticsGrpcAsyncIOTransport +from .transports.rest import LiveVideoAnalyticsRestTransport + + +class LiveVideoAnalyticsClientMeta(type): + """Metaclass for the LiveVideoAnalytics 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[LiveVideoAnalyticsTransport]] + _transport_registry["grpc"] = LiveVideoAnalyticsGrpcTransport + _transport_registry["grpc_asyncio"] = LiveVideoAnalyticsGrpcAsyncIOTransport + _transport_registry["rest"] = LiveVideoAnalyticsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LiveVideoAnalyticsTransport]: + """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 LiveVideoAnalyticsClient(metaclass=LiveVideoAnalyticsClientMeta): + """Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + LiveVideoAnalyticsClient: 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: + LiveVideoAnalyticsClient: 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) -> LiveVideoAnalyticsTransport: + """Returns the transport used by the client instance. + + Returns: + LiveVideoAnalyticsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def analysis_path(project: str,location: str,cluster: str,analysis: str,) -> str: + """Returns a fully-qualified analysis string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/analyses/{analysis}".format(project=project, location=location, cluster=cluster, analysis=analysis, ) + + @staticmethod + def parse_analysis_path(path: str) -> Dict[str,str]: + """Parses a analysis path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/analyses/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + LiveVideoAnalyticsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LiveVideoAnalyticsTransport, Callable[..., LiveVideoAnalyticsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the live video analytics 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 (Optional[Union[str,LiveVideoAnalyticsTransport,Callable[..., LiveVideoAnalyticsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LiveVideoAnalyticsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LiveVideoAnalyticsClient._read_environment_variables() + self._client_cert_source = LiveVideoAnalyticsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LiveVideoAnalyticsClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, LiveVideoAnalyticsTransport) + if transport_provided: + # transport is a LiveVideoAnalyticsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(LiveVideoAnalyticsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LiveVideoAnalyticsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[LiveVideoAnalyticsTransport], Callable[..., LiveVideoAnalyticsTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LiveVideoAnalyticsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_analyses(self, + request: Optional[Union[lva_service.ListAnalysesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnalysesPager: + r"""Lists Analyses in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_analyses(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListAnalysesRequest, dict]): + The request object. Message for requesting list of + Analyses + parent (str): + Required. Parent value for + ListAnalysesRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.live_video_analytics.pagers.ListAnalysesPager: + Message for response to listing + Analyses + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.ListAnalysesRequest): + request = lva_service.ListAnalysesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_analyses] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAnalysesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_analysis(self, + request: Optional[Union[lva_service.GetAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lva_resources.Analysis: + r"""Gets details of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = client.get_analysis(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetAnalysisRequest, dict]): + The request object. Message for getting an Analysis. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Analysis: + Message describing the Analysis + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.GetAnalysisRequest): + request = lva_service.GetAnalysisRequest(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_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_analysis(self, + request: Optional[Union[lva_service.CreateAnalysisRequest, dict]] = None, + *, + parent: Optional[str] = None, + analysis: Optional[lva_resources.Analysis] = None, + analysis_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Analysis in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateAnalysisRequest, dict]): + The request object. Message for creating an Analysis. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis (google.cloud.visionai_v1alpha1.types.Analysis): + Required. The resource being created. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + analysis_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``analysis_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Analysis` + Message describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, analysis, analysis_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.CreateAnalysisRequest): + request = lva_service.CreateAnalysisRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if analysis is not None: + request.analysis = analysis + if analysis_id is not None: + request.analysis_id = analysis_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_analysis(self, + request: Optional[Union[lva_service.UpdateAnalysisRequest, dict]] = None, + *, + analysis: Optional[lva_resources.Analysis] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateAnalysisRequest, dict]): + The request object. Message for updating an Analysis. + analysis (google.cloud.visionai_v1alpha1.types.Analysis): + Required. The resource being updated. + This corresponds to the ``analysis`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Analysis resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Analysis` + Message describing the Analysis object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([analysis, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.UpdateAnalysisRequest): + request = lva_service.UpdateAnalysisRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if analysis is not None: + request.analysis = analysis + 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_analysis] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis.name", request.analysis.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + lva_resources.Analysis, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_analysis(self, + request: Optional[Union[lva_service.DeleteAnalysisRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Analysis. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteAnalysisRequest, dict]): + The request object. Message for deleting an Analysis. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, lva_service.DeleteAnalysisRequest): + request = lva_service.DeleteAnalysisRequest(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_analysis] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LiveVideoAnalyticsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "LiveVideoAnalyticsClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/pagers.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/pagers.py new file mode 100644 index 000000000000..206acbbf218c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service + + +class ListAnalysesPager: + """A pager for iterating through ``list_analyses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListAnalysesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``analyses`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnalyses`` requests and continue to iterate + through the ``analyses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListAnalysesResponse` + 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[..., lva_service.ListAnalysesResponse], + request: lva_service.ListAnalysesRequest, + response: lva_service.ListAnalysesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListAnalysesRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListAnalysesResponse): + 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 = lva_service.ListAnalysesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[lva_service.ListAnalysesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[lva_resources.Analysis]: + for page in self.pages: + yield from page.analyses + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnalysesAsyncPager: + """A pager for iterating through ``list_analyses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListAnalysesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``analyses`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnalyses`` requests and continue to iterate + through the ``analyses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListAnalysesResponse` + 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[lva_service.ListAnalysesResponse]], + request: lva_service.ListAnalysesRequest, + response: lva_service.ListAnalysesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListAnalysesRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListAnalysesResponse): + 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 = lva_service.ListAnalysesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[lva_service.ListAnalysesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[lva_resources.Analysis]: + async def async_generator(): + async for page in self.pages: + for response in page.analyses: + 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/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/__init__.py new file mode 100644 index 000000000000..3d5c836f709a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 LiveVideoAnalyticsTransport +from .grpc import LiveVideoAnalyticsGrpcTransport +from .grpc_asyncio import LiveVideoAnalyticsGrpcAsyncIOTransport +from .rest import LiveVideoAnalyticsRestTransport +from .rest import LiveVideoAnalyticsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LiveVideoAnalyticsTransport]] +_transport_registry['grpc'] = LiveVideoAnalyticsGrpcTransport +_transport_registry['grpc_asyncio'] = LiveVideoAnalyticsGrpcAsyncIOTransport +_transport_registry['rest'] = LiveVideoAnalyticsRestTransport + +__all__ = ( + 'LiveVideoAnalyticsTransport', + 'LiveVideoAnalyticsGrpcTransport', + 'LiveVideoAnalyticsGrpcAsyncIOTransport', + 'LiveVideoAnalyticsRestTransport', + 'LiveVideoAnalyticsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/base.py new file mode 100644 index 000000000000..ea929d102aa5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/base.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class LiveVideoAnalyticsTransport(abc.ABC): + """Abstract transport class for LiveVideoAnalytics.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_analyses: gapic_v1.method.wrap_method( + self.list_analyses, + default_timeout=60.0, + client_info=client_info, + ), + self.get_analysis: gapic_v1.method.wrap_method( + self.get_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.create_analysis: gapic_v1.method.wrap_method( + self.create_analysis, + default_timeout=300.0, + client_info=client_info, + ), + self.update_analysis: gapic_v1.method.wrap_method( + self.update_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_analysis: gapic_v1.method.wrap_method( + self.delete_analysis, + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + Union[ + lva_service.ListAnalysesResponse, + Awaitable[lva_service.ListAnalysesResponse] + ]]: + raise NotImplementedError() + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + Union[ + lva_resources.Analysis, + Awaitable[lva_resources.Analysis] + ]]: + raise NotImplementedError() + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LiveVideoAnalyticsTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/grpc.py new file mode 100644 index 000000000000..33d0d051e043 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/grpc.py @@ -0,0 +1,586 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO + + +class LiveVideoAnalyticsGrpcTransport(LiveVideoAnalyticsTransport): + """gRPC backend transport for LiveVideoAnalytics. + + Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + lva_service.ListAnalysesResponse]: + r"""Return a callable for the list analyses method over gRPC. + + Lists Analyses in a given project and location. + + Returns: + Callable[[~.ListAnalysesRequest], + ~.ListAnalysesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analyses' not in self._stubs: + self._stubs['list_analyses'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/ListAnalyses', + request_serializer=lva_service.ListAnalysesRequest.serialize, + response_deserializer=lva_service.ListAnalysesResponse.deserialize, + ) + return self._stubs['list_analyses'] + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + lva_resources.Analysis]: + r"""Return a callable for the get analysis method over gRPC. + + Gets details of a single Analysis. + + Returns: + Callable[[~.GetAnalysisRequest], + ~.Analysis]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analysis' not in self._stubs: + self._stubs['get_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/GetAnalysis', + request_serializer=lva_service.GetAnalysisRequest.serialize, + response_deserializer=lva_resources.Analysis.deserialize, + ) + return self._stubs['get_analysis'] + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + operations_pb2.Operation]: + r"""Return a callable for the create analysis method over gRPC. + + Creates a new Analysis in a given project and + location. + + Returns: + Callable[[~.CreateAnalysisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_analysis' not in self._stubs: + self._stubs['create_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/CreateAnalysis', + request_serializer=lva_service.CreateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_analysis'] + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + operations_pb2.Operation]: + r"""Return a callable for the update analysis method over gRPC. + + Updates the parameters of a single Analysis. + + Returns: + Callable[[~.UpdateAnalysisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_analysis' not in self._stubs: + self._stubs['update_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/UpdateAnalysis', + request_serializer=lva_service.UpdateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_analysis'] + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete analysis method over gRPC. + + Deletes a single Analysis. + + Returns: + Callable[[~.DeleteAnalysisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_analysis' not in self._stubs: + self._stubs['delete_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/DeleteAnalysis', + request_serializer=lva_service.DeleteAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_analysis'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LiveVideoAnalyticsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/grpc_asyncio.py new file mode 100644 index 000000000000..a537ad536729 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/grpc_asyncio.py @@ -0,0 +1,616 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO +from .grpc import LiveVideoAnalyticsGrpcTransport + + +class LiveVideoAnalyticsGrpcAsyncIOTransport(LiveVideoAnalyticsTransport): + """gRPC AsyncIO backend transport for LiveVideoAnalytics. + + Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + Awaitable[lva_service.ListAnalysesResponse]]: + r"""Return a callable for the list analyses method over gRPC. + + Lists Analyses in a given project and location. + + Returns: + Callable[[~.ListAnalysesRequest], + Awaitable[~.ListAnalysesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analyses' not in self._stubs: + self._stubs['list_analyses'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/ListAnalyses', + request_serializer=lva_service.ListAnalysesRequest.serialize, + response_deserializer=lva_service.ListAnalysesResponse.deserialize, + ) + return self._stubs['list_analyses'] + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + Awaitable[lva_resources.Analysis]]: + r"""Return a callable for the get analysis method over gRPC. + + Gets details of a single Analysis. + + Returns: + Callable[[~.GetAnalysisRequest], + Awaitable[~.Analysis]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_analysis' not in self._stubs: + self._stubs['get_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/GetAnalysis', + request_serializer=lva_service.GetAnalysisRequest.serialize, + response_deserializer=lva_resources.Analysis.deserialize, + ) + return self._stubs['get_analysis'] + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create analysis method over gRPC. + + Creates a new Analysis in a given project and + location. + + Returns: + Callable[[~.CreateAnalysisRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_analysis' not in self._stubs: + self._stubs['create_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/CreateAnalysis', + request_serializer=lva_service.CreateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_analysis'] + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update analysis method over gRPC. + + Updates the parameters of a single Analysis. + + Returns: + Callable[[~.UpdateAnalysisRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_analysis' not in self._stubs: + self._stubs['update_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/UpdateAnalysis', + request_serializer=lva_service.UpdateAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_analysis'] + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete analysis method over gRPC. + + Deletes a single Analysis. + + Returns: + Callable[[~.DeleteAnalysisRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_analysis' not in self._stubs: + self._stubs['delete_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.LiveVideoAnalytics/DeleteAnalysis', + request_serializer=lva_service.DeleteAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_analysis'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_analyses: gapic_v1.method_async.wrap_method( + self.list_analyses, + default_timeout=60.0, + client_info=client_info, + ), + self.get_analysis: gapic_v1.method_async.wrap_method( + self.get_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.create_analysis: gapic_v1.method_async.wrap_method( + self.create_analysis, + default_timeout=300.0, + client_info=client_info, + ), + self.update_analysis: gapic_v1.method_async.wrap_method( + self.update_analysis, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_analysis: gapic_v1.method_async.wrap_method( + self.delete_analysis, + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'LiveVideoAnalyticsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/rest.py new file mode 100644 index 000000000000..e499d35aaf0c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/live_video_analytics/transports/rest.py @@ -0,0 +1,1669 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import LiveVideoAnalyticsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class LiveVideoAnalyticsRestInterceptor: + """Interceptor for LiveVideoAnalytics. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the LiveVideoAnalyticsRestTransport. + + .. code-block:: python + class MyCustomLiveVideoAnalyticsInterceptor(LiveVideoAnalyticsRestInterceptor): + def pre_create_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_analyses(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_analyses(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_analysis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_analysis(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LiveVideoAnalyticsRestTransport(interceptor=MyCustomLiveVideoAnalyticsInterceptor()) + client = LiveVideoAnalyticsClient(transport=transport) + + + """ + def pre_create_analysis(self, request: lva_service.CreateAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.CreateAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_create_analysis(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_delete_analysis(self, request: lva_service.DeleteAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.DeleteAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_delete_analysis(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_get_analysis(self, request: lva_service.GetAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.GetAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_analysis(self, response: lva_resources.Analysis) -> lva_resources.Analysis: + """Post-rpc interceptor for get_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_analyses(self, request: lva_service.ListAnalysesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.ListAnalysesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_analyses + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_analyses(self, response: lva_service.ListAnalysesResponse) -> lva_service.ListAnalysesResponse: + """Post-rpc interceptor for list_analyses + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_update_analysis(self, request: lva_service.UpdateAnalysisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[lva_service.UpdateAnalysisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_analysis + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_update_analysis(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_analysis + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the LiveVideoAnalytics server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the LiveVideoAnalytics server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LiveVideoAnalyticsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LiveVideoAnalyticsRestInterceptor + + +class LiveVideoAnalyticsRestTransport(LiveVideoAnalyticsTransport): + """REST backend transport for LiveVideoAnalytics. + + Service describing handlers for resources. The service + enables clients to run Live Video Analytics (LVA) on the + streaming inputs. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[LiveVideoAnalyticsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or LiveVideoAnalyticsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("CreateAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "analysisId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.CreateAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create analysis method over HTTP. + + Args: + request (~.lva_service.CreateAnalysisRequest): + The request object. Message for creating an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/analyses', + 'body': 'analysis', + }, + ] + request, metadata = self._interceptor.pre_create_analysis(request, metadata) + pb_request = lva_service.CreateAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_analysis(resp) + return resp + + class _DeleteAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("DeleteAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.DeleteAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete analysis method over HTTP. + + Args: + request (~.lva_service.DeleteAnalysisRequest): + The request object. Message for deleting an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/analyses/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_analysis(request, metadata) + pb_request = lva_service.DeleteAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_analysis(resp) + return resp + + class _GetAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("GetAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.GetAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_resources.Analysis: + r"""Call the get analysis method over HTTP. + + Args: + request (~.lva_service.GetAnalysisRequest): + The request object. Message for getting an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_resources.Analysis: + Message describing the Analysis + object. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/analyses/*}', + }, + ] + request, metadata = self._interceptor.pre_get_analysis(request, metadata) + pb_request = lva_service.GetAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_resources.Analysis() + pb_resp = lva_resources.Analysis.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_analysis(resp) + return resp + + class _ListAnalyses(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("ListAnalyses") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.ListAnalysesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> lva_service.ListAnalysesResponse: + r"""Call the list analyses method over HTTP. + + Args: + request (~.lva_service.ListAnalysesRequest): + The request object. Message for requesting list of + Analyses + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lva_service.ListAnalysesResponse: + Message for response to listing + Analyses + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/analyses', + }, + ] + request, metadata = self._interceptor.pre_list_analyses(request, metadata) + pb_request = lva_service.ListAnalysesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = lva_service.ListAnalysesResponse() + pb_resp = lva_service.ListAnalysesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_analyses(resp) + return resp + + class _UpdateAnalysis(LiveVideoAnalyticsRestStub): + def __hash__(self): + return hash("UpdateAnalysis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: lva_service.UpdateAnalysisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update analysis method over HTTP. + + Args: + request (~.lva_service.UpdateAnalysisRequest): + The request object. Message for updating an Analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{analysis.name=projects/*/locations/*/clusters/*/analyses/*}', + 'body': 'analysis', + }, + ] + request, metadata = self._interceptor.pre_update_analysis(request, metadata) + pb_request = lva_service.UpdateAnalysisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_analysis(resp) + return resp + + @property + def create_analysis(self) -> Callable[ + [lva_service.CreateAnalysisRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_analysis(self) -> Callable[ + [lva_service.DeleteAnalysisRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_analysis(self) -> Callable[ + [lva_service.GetAnalysisRequest], + lva_resources.Analysis]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_analyses(self) -> Callable[ + [lva_service.ListAnalysesRequest], + lva_service.ListAnalysesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAnalyses(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_analysis(self) -> Callable[ + [lva_service.UpdateAnalysisRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAnalysis(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(LiveVideoAnalyticsRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(LiveVideoAnalyticsRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(LiveVideoAnalyticsRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(LiveVideoAnalyticsRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(LiveVideoAnalyticsRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(LiveVideoAnalyticsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LiveVideoAnalyticsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/__init__.py new file mode 100644 index 000000000000..f39d9fd3b046 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamingServiceClient +from .async_client import StreamingServiceAsyncClient + +__all__ = ( + 'StreamingServiceClient', + 'StreamingServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/async_client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/async_client.py new file mode 100644 index 000000000000..4880b54b86d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/async_client.py @@ -0,0 +1,1338 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import streaming_resources +from google.cloud.visionai_v1alpha1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import StreamingServiceGrpcAsyncIOTransport +from .client import StreamingServiceClient + + +class StreamingServiceAsyncClient: + """Streaming service for receiving and sending packets.""" + + _client: StreamingServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = StreamingServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = StreamingServiceClient._DEFAULT_UNIVERSE + + series_path = staticmethod(StreamingServiceClient.series_path) + parse_series_path = staticmethod(StreamingServiceClient.parse_series_path) + common_billing_account_path = staticmethod(StreamingServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(StreamingServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(StreamingServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(StreamingServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(StreamingServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(StreamingServiceClient.parse_common_organization_path) + common_project_path = staticmethod(StreamingServiceClient.common_project_path) + parse_common_project_path = staticmethod(StreamingServiceClient.parse_common_project_path) + common_location_path = staticmethod(StreamingServiceClient.common_location_path) + parse_common_location_path = staticmethod(StreamingServiceClient.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: + StreamingServiceAsyncClient: The constructed client. + """ + return StreamingServiceClient.from_service_account_info.__func__(StreamingServiceAsyncClient, 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: + StreamingServiceAsyncClient: The constructed client. + """ + return StreamingServiceClient.from_service_account_file.__func__(StreamingServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return StreamingServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> StreamingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamingServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(StreamingServiceClient).get_transport_class, type(StreamingServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamingServiceTransport, Callable[..., StreamingServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streaming service async 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 (Optional[Union[str,StreamingServiceTransport,Callable[..., StreamingServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamingServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = StreamingServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + def send_packets(self, + requests: Optional[AsyncIterator[streaming_service.SendPacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[streaming_service.SendPacketsResponse]]: + r"""Send packets to the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_send_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.send_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1alpha1.types.SendPacketsRequest`]): + The request object AsyncIterator. Request message for sending packets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1alpha1.types.SendPacketsResponse]: + Response message for sending packets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.send_packets] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_packets(self, + requests: Optional[AsyncIterator[streaming_service.ReceivePacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[streaming_service.ReceivePacketsResponse]]: + r"""Receive packets from the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_receive_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1alpha1.types.ReceivePacketsRequest`]): + The request object AsyncIterator. Request message for receiving + packets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1alpha1.types.ReceivePacketsResponse]: + Response message from ReceivePackets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.receive_packets] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_events(self, + requests: Optional[AsyncIterator[streaming_service.ReceiveEventsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[streaming_service.ReceiveEventsResponse]]: + r"""Receive events given the stream name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_receive_events(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_events(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1alpha1.types.ReceiveEventsRequest`]): + The request object AsyncIterator. Request message for ReceiveEvents. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1alpha1.types.ReceiveEventsResponse]: + Response message for the + ReceiveEvents. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.receive_events] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def acquire_lease(self, + request: Optional[Union[streaming_service.AcquireLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""AcquireLease acquires a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_acquire_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AcquireLeaseRequest( + ) + + # Make the request + response = await client.acquire_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.AcquireLeaseRequest, dict]]): + The request object. Request message for acquiring a + lease. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.AcquireLeaseRequest): + request = streaming_service.AcquireLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.acquire_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def renew_lease(self, + request: Optional[Union[streaming_service.RenewLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""RenewLease renews a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_renew_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RenewLeaseRequest( + ) + + # Make the request + response = await client.renew_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.RenewLeaseRequest, dict]]): + The request object. Request message for renewing a lease. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.RenewLeaseRequest): + request = streaming_service.RenewLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.renew_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def release_lease(self, + request: Optional[Union[streaming_service.ReleaseLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.ReleaseLeaseResponse: + r"""RleaseLease releases a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_release_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReleaseLeaseRequest( + ) + + # Make the request + response = await client.release_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ReleaseLeaseRequest, dict]]): + The request object. Request message for releasing lease. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.ReleaseLeaseResponse: + Response message for release lease. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.ReleaseLeaseRequest): + request = streaming_service.ReleaseLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.release_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "StreamingServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamingServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/client.py new file mode 100644 index 000000000000..1bb4545cb0d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/client.py @@ -0,0 +1,1690 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import streaming_resources +from google.cloud.visionai_v1alpha1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamingServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import StreamingServiceGrpcTransport +from .transports.grpc_asyncio import StreamingServiceGrpcAsyncIOTransport +from .transports.rest import StreamingServiceRestTransport + + +class StreamingServiceClientMeta(type): + """Metaclass for the StreamingService 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[StreamingServiceTransport]] + _transport_registry["grpc"] = StreamingServiceGrpcTransport + _transport_registry["grpc_asyncio"] = StreamingServiceGrpcAsyncIOTransport + _transport_registry["rest"] = StreamingServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[StreamingServiceTransport]: + """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 StreamingServiceClient(metaclass=StreamingServiceClientMeta): + """Streaming service for receiving and sending packets.""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + StreamingServiceClient: 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: + StreamingServiceClient: 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) -> StreamingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamingServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def series_path(project: str,location: str,cluster: str,series: str,) -> str: + """Returns a fully-qualified series string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + + @staticmethod + def parse_series_path(path: str) -> Dict[str,str]: + """Parses a series path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/series/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = StreamingServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + StreamingServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamingServiceTransport, Callable[..., StreamingServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streaming service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,StreamingServiceTransport,Callable[..., StreamingServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamingServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StreamingServiceClient._read_environment_variables() + self._client_cert_source = StreamingServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = StreamingServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, StreamingServiceTransport) + if transport_provided: + # transport is a StreamingServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(StreamingServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + StreamingServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[StreamingServiceTransport], Callable[..., StreamingServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., StreamingServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def send_packets(self, + requests: Optional[Iterator[streaming_service.SendPacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[streaming_service.SendPacketsResponse]: + r"""Send packets to the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_send_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.send_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1alpha1.types.SendPacketsRequest]): + The request object iterator. Request message for sending packets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1alpha1.types.SendPacketsResponse]: + Response message for sending packets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_packets] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_packets(self, + requests: Optional[Iterator[streaming_service.ReceivePacketsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[streaming_service.ReceivePacketsResponse]: + r"""Receive packets from the series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_receive_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1alpha1.types.ReceivePacketsRequest]): + The request object iterator. Request message for receiving + packets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1alpha1.types.ReceivePacketsResponse]: + Response message from ReceivePackets. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.receive_packets] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def receive_events(self, + requests: Optional[Iterator[streaming_service.ReceiveEventsRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[streaming_service.ReceiveEventsResponse]: + r"""Receive events given the stream name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_receive_events(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_events(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1alpha1.types.ReceiveEventsRequest]): + The request object iterator. Request message for ReceiveEvents. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1alpha1.types.ReceiveEventsResponse]: + Response message for the + ReceiveEvents. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.receive_events] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def acquire_lease(self, + request: Optional[Union[streaming_service.AcquireLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""AcquireLease acquires a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_acquire_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AcquireLeaseRequest( + ) + + # Make the request + response = client.acquire_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.AcquireLeaseRequest, dict]): + The request object. Request message for acquiring a + lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.AcquireLeaseRequest): + request = streaming_service.AcquireLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.acquire_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def renew_lease(self, + request: Optional[Union[streaming_service.RenewLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.Lease: + r"""RenewLease renews a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_renew_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RenewLeaseRequest( + ) + + # Make the request + response = client.renew_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.RenewLeaseRequest, dict]): + The request object. Request message for renewing a lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Lease: + The lease message. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.RenewLeaseRequest): + request = streaming_service.RenewLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.renew_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def release_lease(self, + request: Optional[Union[streaming_service.ReleaseLeaseRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streaming_service.ReleaseLeaseResponse: + r"""RleaseLease releases a lease. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_release_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReleaseLeaseRequest( + ) + + # Make the request + response = client.release_lease(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ReleaseLeaseRequest, dict]): + The request object. Request message for releasing lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.ReleaseLeaseResponse: + Response message for release lease. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streaming_service.ReleaseLeaseRequest): + request = streaming_service.ReleaseLeaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.release_lease] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series", request.series), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "StreamingServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamingServiceClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/__init__.py new file mode 100644 index 000000000000..6136e80c250d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamingServiceTransport +from .grpc import StreamingServiceGrpcTransport +from .grpc_asyncio import StreamingServiceGrpcAsyncIOTransport +from .rest import StreamingServiceRestTransport +from .rest import StreamingServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StreamingServiceTransport]] +_transport_registry['grpc'] = StreamingServiceGrpcTransport +_transport_registry['grpc_asyncio'] = StreamingServiceGrpcAsyncIOTransport +_transport_registry['rest'] = StreamingServiceRestTransport + +__all__ = ( + 'StreamingServiceTransport', + 'StreamingServiceGrpcTransport', + 'StreamingServiceGrpcAsyncIOTransport', + 'StreamingServiceRestTransport', + 'StreamingServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/base.py new file mode 100644 index 000000000000..a90a8f3ef3fd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/base.py @@ -0,0 +1,308 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class StreamingServiceTransport(abc.ABC): + """Abstract transport class for StreamingService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.send_packets: gapic_v1.method.wrap_method( + self.send_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_packets: gapic_v1.method.wrap_method( + self.receive_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_events: gapic_v1.method.wrap_method( + self.receive_events, + default_timeout=None, + client_info=client_info, + ), + self.acquire_lease: gapic_v1.method.wrap_method( + self.acquire_lease, + default_timeout=None, + client_info=client_info, + ), + self.renew_lease: gapic_v1.method.wrap_method( + self.renew_lease, + default_timeout=None, + client_info=client_info, + ), + self.release_lease: gapic_v1.method.wrap_method( + self.release_lease, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + Union[ + streaming_service.SendPacketsResponse, + Awaitable[streaming_service.SendPacketsResponse] + ]]: + raise NotImplementedError() + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + Union[ + streaming_service.ReceivePacketsResponse, + Awaitable[streaming_service.ReceivePacketsResponse] + ]]: + raise NotImplementedError() + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + Union[ + streaming_service.ReceiveEventsResponse, + Awaitable[streaming_service.ReceiveEventsResponse] + ]]: + raise NotImplementedError() + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + Union[ + streaming_service.Lease, + Awaitable[streaming_service.Lease] + ]]: + raise NotImplementedError() + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + Union[ + streaming_service.Lease, + Awaitable[streaming_service.Lease] + ]]: + raise NotImplementedError() + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + Union[ + streaming_service.ReleaseLeaseResponse, + Awaitable[streaming_service.ReleaseLeaseResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'StreamingServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/grpc.py new file mode 100644 index 000000000000..b68f803cf1ee --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/grpc.py @@ -0,0 +1,590 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamingServiceTransport, DEFAULT_CLIENT_INFO + + +class StreamingServiceGrpcTransport(StreamingServiceTransport): + """gRPC backend transport for StreamingService. + + Streaming service for receiving and sending packets. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance 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 isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[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 send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + streaming_service.SendPacketsResponse]: + r"""Return a callable for the send packets method over gRPC. + + Send packets to the series. + + Returns: + Callable[[~.SendPacketsRequest], + ~.SendPacketsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'send_packets' not in self._stubs: + self._stubs['send_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.StreamingService/SendPackets', + request_serializer=streaming_service.SendPacketsRequest.serialize, + response_deserializer=streaming_service.SendPacketsResponse.deserialize, + ) + return self._stubs['send_packets'] + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + streaming_service.ReceivePacketsResponse]: + r"""Return a callable for the receive packets method over gRPC. + + Receive packets from the series. + + Returns: + Callable[[~.ReceivePacketsRequest], + ~.ReceivePacketsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_packets' not in self._stubs: + self._stubs['receive_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.StreamingService/ReceivePackets', + request_serializer=streaming_service.ReceivePacketsRequest.serialize, + response_deserializer=streaming_service.ReceivePacketsResponse.deserialize, + ) + return self._stubs['receive_packets'] + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + streaming_service.ReceiveEventsResponse]: + r"""Return a callable for the receive events method over gRPC. + + Receive events given the stream name. + + Returns: + Callable[[~.ReceiveEventsRequest], + ~.ReceiveEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_events' not in self._stubs: + self._stubs['receive_events'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.StreamingService/ReceiveEvents', + request_serializer=streaming_service.ReceiveEventsRequest.serialize, + response_deserializer=streaming_service.ReceiveEventsResponse.deserialize, + ) + return self._stubs['receive_events'] + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + streaming_service.Lease]: + r"""Return a callable for the acquire lease method over gRPC. + + AcquireLease acquires a lease. + + Returns: + Callable[[~.AcquireLeaseRequest], + ~.Lease]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acquire_lease' not in self._stubs: + self._stubs['acquire_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamingService/AcquireLease', + request_serializer=streaming_service.AcquireLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['acquire_lease'] + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + streaming_service.Lease]: + r"""Return a callable for the renew lease method over gRPC. + + RenewLease renews a lease. + + Returns: + Callable[[~.RenewLeaseRequest], + ~.Lease]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'renew_lease' not in self._stubs: + self._stubs['renew_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamingService/RenewLease', + request_serializer=streaming_service.RenewLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['renew_lease'] + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + streaming_service.ReleaseLeaseResponse]: + r"""Return a callable for the release lease method over gRPC. + + RleaseLease releases a lease. + + Returns: + Callable[[~.ReleaseLeaseRequest], + ~.ReleaseLeaseResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'release_lease' not in self._stubs: + self._stubs['release_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamingService/ReleaseLease', + request_serializer=streaming_service.ReleaseLeaseRequest.serialize, + response_deserializer=streaming_service.ReleaseLeaseResponse.deserialize, + ) + return self._stubs['release_lease'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'StreamingServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..591ab7a5c232 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/grpc_asyncio.py @@ -0,0 +1,625 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamingServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import StreamingServiceGrpcTransport + + +class StreamingServiceGrpcAsyncIOTransport(StreamingServiceTransport): + """gRPC AsyncIO backend transport for StreamingService. + + Streaming service for receiving and sending packets. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance 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 isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + Awaitable[streaming_service.SendPacketsResponse]]: + r"""Return a callable for the send packets method over gRPC. + + Send packets to the series. + + Returns: + Callable[[~.SendPacketsRequest], + Awaitable[~.SendPacketsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'send_packets' not in self._stubs: + self._stubs['send_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.StreamingService/SendPackets', + request_serializer=streaming_service.SendPacketsRequest.serialize, + response_deserializer=streaming_service.SendPacketsResponse.deserialize, + ) + return self._stubs['send_packets'] + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + Awaitable[streaming_service.ReceivePacketsResponse]]: + r"""Return a callable for the receive packets method over gRPC. + + Receive packets from the series. + + Returns: + Callable[[~.ReceivePacketsRequest], + Awaitable[~.ReceivePacketsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_packets' not in self._stubs: + self._stubs['receive_packets'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.StreamingService/ReceivePackets', + request_serializer=streaming_service.ReceivePacketsRequest.serialize, + response_deserializer=streaming_service.ReceivePacketsResponse.deserialize, + ) + return self._stubs['receive_packets'] + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + Awaitable[streaming_service.ReceiveEventsResponse]]: + r"""Return a callable for the receive events method over gRPC. + + Receive events given the stream name. + + Returns: + Callable[[~.ReceiveEventsRequest], + Awaitable[~.ReceiveEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'receive_events' not in self._stubs: + self._stubs['receive_events'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.StreamingService/ReceiveEvents', + request_serializer=streaming_service.ReceiveEventsRequest.serialize, + response_deserializer=streaming_service.ReceiveEventsResponse.deserialize, + ) + return self._stubs['receive_events'] + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + Awaitable[streaming_service.Lease]]: + r"""Return a callable for the acquire lease method over gRPC. + + AcquireLease acquires a lease. + + Returns: + Callable[[~.AcquireLeaseRequest], + Awaitable[~.Lease]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acquire_lease' not in self._stubs: + self._stubs['acquire_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamingService/AcquireLease', + request_serializer=streaming_service.AcquireLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['acquire_lease'] + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + Awaitable[streaming_service.Lease]]: + r"""Return a callable for the renew lease method over gRPC. + + RenewLease renews a lease. + + Returns: + Callable[[~.RenewLeaseRequest], + Awaitable[~.Lease]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'renew_lease' not in self._stubs: + self._stubs['renew_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamingService/RenewLease', + request_serializer=streaming_service.RenewLeaseRequest.serialize, + response_deserializer=streaming_service.Lease.deserialize, + ) + return self._stubs['renew_lease'] + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + Awaitable[streaming_service.ReleaseLeaseResponse]]: + r"""Return a callable for the release lease method over gRPC. + + RleaseLease releases a lease. + + Returns: + Callable[[~.ReleaseLeaseRequest], + Awaitable[~.ReleaseLeaseResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'release_lease' not in self._stubs: + self._stubs['release_lease'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamingService/ReleaseLease', + request_serializer=streaming_service.ReleaseLeaseRequest.serialize, + response_deserializer=streaming_service.ReleaseLeaseResponse.deserialize, + ) + return self._stubs['release_lease'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.send_packets: gapic_v1.method_async.wrap_method( + self.send_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_packets: gapic_v1.method_async.wrap_method( + self.receive_packets, + default_timeout=None, + client_info=client_info, + ), + self.receive_events: gapic_v1.method_async.wrap_method( + self.receive_events, + default_timeout=None, + client_info=client_info, + ), + self.acquire_lease: gapic_v1.method_async.wrap_method( + self.acquire_lease, + default_timeout=None, + client_info=client_info, + ), + self.renew_lease: gapic_v1.method_async.wrap_method( + self.renew_lease, + default_timeout=None, + client_info=client_info, + ), + self.release_lease: gapic_v1.method_async.wrap_method( + self.release_lease, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'StreamingServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/rest.py new file mode 100644 index 000000000000..b8b814bd3cbd --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streaming_service/transports/rest.py @@ -0,0 +1,1429 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1alpha1.types import streaming_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import StreamingServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class StreamingServiceRestInterceptor: + """Interceptor for StreamingService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the StreamingServiceRestTransport. + + .. code-block:: python + class MyCustomStreamingServiceInterceptor(StreamingServiceRestInterceptor): + def pre_acquire_lease(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_acquire_lease(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_release_lease(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_release_lease(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_renew_lease(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_renew_lease(self, response): + logging.log(f"Received response: {response}") + return response + + transport = StreamingServiceRestTransport(interceptor=MyCustomStreamingServiceInterceptor()) + client = StreamingServiceClient(transport=transport) + + + """ + def pre_acquire_lease(self, request: streaming_service.AcquireLeaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streaming_service.AcquireLeaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for acquire_lease + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_acquire_lease(self, response: streaming_service.Lease) -> streaming_service.Lease: + """Post-rpc interceptor for acquire_lease + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_release_lease(self, request: streaming_service.ReleaseLeaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streaming_service.ReleaseLeaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for release_lease + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_release_lease(self, response: streaming_service.ReleaseLeaseResponse) -> streaming_service.ReleaseLeaseResponse: + """Post-rpc interceptor for release_lease + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_renew_lease(self, request: streaming_service.RenewLeaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streaming_service.RenewLeaseRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for renew_lease + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_renew_lease(self, response: streaming_service.Lease) -> streaming_service.Lease: + """Post-rpc interceptor for renew_lease + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamingService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the StreamingService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class StreamingServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: StreamingServiceRestInterceptor + + +class StreamingServiceRestTransport(StreamingServiceTransport): + """REST backend transport for StreamingService. + + Streaming service for receiving and sending packets. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[StreamingServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or StreamingServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AcquireLease(StreamingServiceRestStub): + def __hash__(self): + return hash("AcquireLease") + + def __call__(self, + request: streaming_service.AcquireLeaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streaming_service.Lease: + r"""Call the acquire lease method over HTTP. + + Args: + request (~.streaming_service.AcquireLeaseRequest): + The request object. Request message for acquiring a + lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streaming_service.Lease: + The lease message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{series=projects/*/locations/*/clusters/*/series/*}:acquireLease', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_acquire_lease(request, metadata) + pb_request = streaming_service.AcquireLeaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streaming_service.Lease() + pb_resp = streaming_service.Lease.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_acquire_lease(resp) + return resp + + class _ReceiveEvents(StreamingServiceRestStub): + def __hash__(self): + return hash("ReceiveEvents") + + def __call__(self, + request: streaming_service.ReceiveEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method ReceiveEvents is not available over REST transport" + ) + class _ReceivePackets(StreamingServiceRestStub): + def __hash__(self): + return hash("ReceivePackets") + + def __call__(self, + request: streaming_service.ReceivePacketsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method ReceivePackets is not available over REST transport" + ) + class _ReleaseLease(StreamingServiceRestStub): + def __hash__(self): + return hash("ReleaseLease") + + def __call__(self, + request: streaming_service.ReleaseLeaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streaming_service.ReleaseLeaseResponse: + r"""Call the release lease method over HTTP. + + Args: + request (~.streaming_service.ReleaseLeaseRequest): + The request object. Request message for releasing lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streaming_service.ReleaseLeaseResponse: + Response message for release lease. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{series=projects/*/locations/*/clusters/*/series/*}:releaseLease', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_release_lease(request, metadata) + pb_request = streaming_service.ReleaseLeaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streaming_service.ReleaseLeaseResponse() + pb_resp = streaming_service.ReleaseLeaseResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_release_lease(resp) + return resp + + class _RenewLease(StreamingServiceRestStub): + def __hash__(self): + return hash("RenewLease") + + def __call__(self, + request: streaming_service.RenewLeaseRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streaming_service.Lease: + r"""Call the renew lease method over HTTP. + + Args: + request (~.streaming_service.RenewLeaseRequest): + The request object. Request message for renewing a lease. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streaming_service.Lease: + The lease message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{series=projects/*/locations/*/clusters/*/series/*}:renewLease', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_renew_lease(request, metadata) + pb_request = streaming_service.RenewLeaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streaming_service.Lease() + pb_resp = streaming_service.Lease.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_renew_lease(resp) + return resp + + class _SendPackets(StreamingServiceRestStub): + def __hash__(self): + return hash("SendPackets") + + def __call__(self, + request: streaming_service.SendPacketsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method SendPackets is not available over REST transport" + ) + + @property + def acquire_lease(self) -> Callable[ + [streaming_service.AcquireLeaseRequest], + streaming_service.Lease]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AcquireLease(self._session, self._host, self._interceptor) # type: ignore + + @property + def receive_events(self) -> Callable[ + [streaming_service.ReceiveEventsRequest], + streaming_service.ReceiveEventsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReceiveEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def receive_packets(self) -> Callable[ + [streaming_service.ReceivePacketsRequest], + streaming_service.ReceivePacketsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReceivePackets(self._session, self._host, self._interceptor) # type: ignore + + @property + def release_lease(self) -> Callable[ + [streaming_service.ReleaseLeaseRequest], + streaming_service.ReleaseLeaseResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReleaseLease(self._session, self._host, self._interceptor) # type: ignore + + @property + def renew_lease(self) -> Callable[ + [streaming_service.RenewLeaseRequest], + streaming_service.Lease]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RenewLease(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_packets(self) -> Callable[ + [streaming_service.SendPacketsRequest], + streaming_service.SendPacketsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SendPackets(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(StreamingServiceRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(StreamingServiceRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(StreamingServiceRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(StreamingServiceRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(StreamingServiceRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(StreamingServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'StreamingServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/__init__.py new file mode 100644 index 000000000000..ee9eade81318 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamsServiceClient +from .async_client import StreamsServiceAsyncClient + +__all__ = ( + 'StreamsServiceClient', + 'StreamsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/async_client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/async_client.py new file mode 100644 index 000000000000..1eec5e400cc3 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/async_client.py @@ -0,0 +1,3538 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.streams_service import pagers +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import StreamsServiceGrpcAsyncIOTransport +from .client import StreamsServiceClient + + +class StreamsServiceAsyncClient: + """Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + """ + + _client: StreamsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = StreamsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = StreamsServiceClient._DEFAULT_UNIVERSE + + channel_path = staticmethod(StreamsServiceClient.channel_path) + parse_channel_path = staticmethod(StreamsServiceClient.parse_channel_path) + cluster_path = staticmethod(StreamsServiceClient.cluster_path) + parse_cluster_path = staticmethod(StreamsServiceClient.parse_cluster_path) + event_path = staticmethod(StreamsServiceClient.event_path) + parse_event_path = staticmethod(StreamsServiceClient.parse_event_path) + series_path = staticmethod(StreamsServiceClient.series_path) + parse_series_path = staticmethod(StreamsServiceClient.parse_series_path) + stream_path = staticmethod(StreamsServiceClient.stream_path) + parse_stream_path = staticmethod(StreamsServiceClient.parse_stream_path) + common_billing_account_path = staticmethod(StreamsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(StreamsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(StreamsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(StreamsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(StreamsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(StreamsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(StreamsServiceClient.common_project_path) + parse_common_project_path = staticmethod(StreamsServiceClient.parse_common_project_path) + common_location_path = staticmethod(StreamsServiceClient.common_location_path) + parse_common_location_path = staticmethod(StreamsServiceClient.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: + StreamsServiceAsyncClient: The constructed client. + """ + return StreamsServiceClient.from_service_account_info.__func__(StreamsServiceAsyncClient, 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: + StreamsServiceAsyncClient: The constructed client. + """ + return StreamsServiceClient.from_service_account_file.__func__(StreamsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return StreamsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> StreamsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(StreamsServiceClient).get_transport_class, type(StreamsServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamsServiceTransport, Callable[..., StreamsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streams service async 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 (Optional[Union[str,StreamsServiceTransport,Callable[..., StreamsServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = StreamsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_clusters(self, + request: Optional[Union[streams_service.ListClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListClustersAsyncPager: + r"""Lists Clusters in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_clusters(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListClustersRequest, dict]]): + The request object. Message for requesting list of + Clusters. + parent (:class:`str`): + Required. Parent value for + ListClustersRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListClustersAsyncPager: + Message for response to listing + Clusters. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListClustersRequest): + request = streams_service.ListClustersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_clusters] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListClustersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_cluster(self, + request: Optional[Union[streams_service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetClusterRequest, dict]]): + The request object. Message for getting a Cluster. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Cluster: + Message describing the Cluster + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetClusterRequest): + request = streams_service.GetClusterRequest(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._client._transport._wrapped_methods[self._client._transport.get_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_cluster(self, + request: Optional[Union[streams_service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[common.Cluster] = None, + cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Cluster in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateClusterRequest, dict]]): + The request object. Message for creating a Cluster. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.visionai_v1alpha1.types.Cluster`): + Required. The resource being created. + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Cluster` + Message describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, cluster, cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateClusterRequest): + request = streams_service.CreateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_cluster(self, + request: Optional[Union[streams_service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[common.Cluster] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateClusterRequest, dict]]): + The request object. Message for updating a Cluster. + cluster (:class:`google.cloud.visionai_v1alpha1.types.Cluster`): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Cluster` + Message describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateClusterRequest): + request = streams_service.UpdateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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._client._transport._wrapped_methods[self._client._transport.update_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster.name", request.cluster.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_cluster(self, + request: Optional[Union[streams_service.DeleteClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteClusterRequest, dict]]): + The request object. Message for deleting a Cluster. + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteClusterRequest): + request = streams_service.DeleteClusterRequest(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._client._transport._wrapped_methods[self._client._transport.delete_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_streams(self, + request: Optional[Union[streams_service.ListStreamsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListStreamsAsyncPager: + r"""Lists Streams in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_streams(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListStreamsRequest, dict]]): + The request object. Message for requesting list of + Streams. + parent (:class:`str`): + Required. Parent value for + ListStreamsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListStreamsAsyncPager: + Message for response to listing + Streams. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListStreamsRequest): + request = streams_service.ListStreamsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_streams] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListStreamsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_stream(self, + request: Optional[Union[streams_service.GetStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Stream: + r"""Gets details of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = await client.get_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetStreamRequest, dict]]): + The request object. Message for getting a Stream. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Stream: + Message describing the Stream object. + The Stream and the Event resources are + many to many; i.e., each Stream resource + can associate to many Event resources + and each Event resource can associate to + many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetStreamRequest): + request = streams_service.GetStreamRequest(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._client._transport._wrapped_methods[self._client._transport.get_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_stream(self, + request: Optional[Union[streams_service.CreateStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + stream: Optional[streams_resources.Stream] = None, + stream_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Stream in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateStreamRequest, dict]]): + The request object. Message for creating a Stream. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream (:class:`google.cloud.visionai_v1alpha1.types.Stream`): + Required. The resource being created. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``stream_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, stream, stream_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateStreamRequest): + request = streams_service.CreateStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if stream is not None: + request.stream = stream + if stream_id is not None: + request.stream_id = stream_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_stream(self, + request: Optional[Union[streams_service.UpdateStreamRequest, dict]] = None, + *, + stream: Optional[streams_resources.Stream] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateStreamRequest, dict]]): + The request object. Message for updating a Stream. + stream (:class:`google.cloud.visionai_v1alpha1.types.Stream`): + Required. The resource being updated. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Stream resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateStreamRequest): + request = streams_service.UpdateStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + 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._client._transport._wrapped_methods[self._client._transport.update_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream.name", request.stream.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_stream(self, + request: Optional[Union[streams_service.DeleteStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteStreamRequest, dict]]): + The request object. Message for deleting a Stream. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteStreamRequest): + request = streams_service.DeleteStreamRequest(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._client._transport._wrapped_methods[self._client._transport.delete_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_stream_hls_token(self, + request: Optional[Union[streams_service.GenerateStreamHlsTokenRequest, dict]] = None, + *, + stream: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_service.GenerateStreamHlsTokenResponse: + r"""Generate the JWT auth token required to get the + stream HLS contents. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = await client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenRequest, dict]]): + The request object. Request message for getting the auth + token to access the stream HLS contents. + stream (:class:`str`): + Required. The name of the stream. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenResponse: + Response message for + GenerateStreamHlsToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GenerateStreamHlsTokenRequest): + request = streams_service.GenerateStreamHlsTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_stream_hls_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream", request.stream), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_events(self, + request: Optional[Union[streams_service.ListEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEventsAsyncPager: + r"""Lists Events in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_events(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListEventsRequest, dict]]): + The request object. Message for requesting list of + Events. + parent (:class:`str`): + Required. Parent value for + ListEventsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListEventsAsyncPager: + Message for response to listing + Events. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListEventsRequest): + request = streams_service.ListEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_events] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListEventsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_event(self, + request: Optional[Union[streams_service.GetEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Event: + r"""Gets details of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetEventRequest, dict]]): + The request object. Message for getting a Event. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Event: + Message describing the Event object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetEventRequest): + request = streams_service.GetEventRequest(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._client._transport._wrapped_methods[self._client._transport.get_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_event(self, + request: Optional[Union[streams_service.CreateEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + event: Optional[streams_resources.Event] = None, + event_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Event in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateEventRequest, dict]]): + The request object. Message for creating a Event. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event (:class:`google.cloud.visionai_v1alpha1.types.Event`): + Required. The resource being created. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``event_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Event` + Message describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event, event_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateEventRequest): + request = streams_service.CreateEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event is not None: + request.event = event + if event_id is not None: + request.event_id = event_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_event(self, + request: Optional[Union[streams_service.UpdateEventRequest, dict]] = None, + *, + event: Optional[streams_resources.Event] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateEventRequest, dict]]): + The request object. Message for updating a Event. + event (:class:`google.cloud.visionai_v1alpha1.types.Event`): + Required. The resource being updated. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Event resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Event` + Message describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateEventRequest): + request = streams_service.UpdateEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event is not None: + request.event = event + 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._client._transport._wrapped_methods[self._client._transport.update_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event.name", request.event.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_event(self, + request: Optional[Union[streams_service.DeleteEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteEventRequest, dict]]): + The request object. Message for deleting a Event. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteEventRequest): + request = streams_service.DeleteEventRequest(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._client._transport._wrapped_methods[self._client._transport.delete_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_series(self, + request: Optional[Union[streams_service.ListSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSeriesAsyncPager: + r"""Lists Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListSeriesRequest, dict]]): + The request object. Message for requesting list of + Series. + parent (:class:`str`): + Required. Parent value for + ListSeriesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListSeriesAsyncPager: + Message for response to listing + Series. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListSeriesRequest): + request = streams_service.ListSeriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListSeriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_series(self, + request: Optional[Union[streams_service.GetSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Series: + r"""Gets details of a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_series(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetSeriesRequest, dict]]): + The request object. Message for getting a Series. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Series: + Message describing the Series object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetSeriesRequest): + request = streams_service.GetSeriesRequest(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._client._transport._wrapped_methods[self._client._transport.get_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_series(self, + request: Optional[Union[streams_service.CreateSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + series: Optional[streams_resources.Series] = None, + series_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateSeriesRequest, dict]]): + The request object. Message for creating a Series. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series (:class:`google.cloud.visionai_v1alpha1.types.Series`): + Required. The resource being created. + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series_id (:class:`str`): + Required. Id of the requesting + object. + + This corresponds to the ``series_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Series` + Message describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, series, series_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateSeriesRequest): + request = streams_service.CreateSeriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if series is not None: + request.series = series + if series_id is not None: + request.series_id = series_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_series(self, + request: Optional[Union[streams_service.UpdateSeriesRequest, dict]] = None, + *, + series: Optional[streams_resources.Series] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateSeriesRequest, dict]]): + The request object. Message for updating a Series. + series (:class:`google.cloud.visionai_v1alpha1.types.Series`): + Required. The resource being updated + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Series resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Series` + Message describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([series, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateSeriesRequest): + request = streams_service.UpdateSeriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if series is not None: + request.series = series + 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._client._transport._wrapped_methods[self._client._transport.update_series] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series.name", request.series.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_series(self, + request: Optional[Union[streams_service.DeleteSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteSeriesRequest, dict]]): + The request object. Message for deleting a Series. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteSeriesRequest): + request = streams_service.DeleteSeriesRequest(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._client._transport._wrapped_methods[self._client._transport.delete_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def materialize_channel(self, + request: Optional[Union[streams_service.MaterializeChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[streams_resources.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Materialize a channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_materialize_channel(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + channel = visionai_v1alpha1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1alpha1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.MaterializeChannelRequest, dict]]): + The request object. Message for materializing a channel. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel (:class:`google.cloud.visionai_v1alpha1.types.Channel`): + Required. The resource being created. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_id (:class:`str`): + Required. Id of the channel. + This corresponds to the ``channel_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Channel` + Message describing the Channel object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel, channel_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.MaterializeChannelRequest): + request = streams_service.MaterializeChannelRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel is not None: + request.channel = channel + if channel_id is not None: + request.channel_id = channel_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.materialize_channel] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + streams_resources.Channel, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "StreamsServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/client.py new file mode 100644 index 000000000000..32d376d8e252 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/client.py @@ -0,0 +1,3904 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.streams_service import pagers +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import StreamsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import StreamsServiceGrpcTransport +from .transports.grpc_asyncio import StreamsServiceGrpcAsyncIOTransport +from .transports.rest import StreamsServiceRestTransport + + +class StreamsServiceClientMeta(type): + """Metaclass for the StreamsService 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[StreamsServiceTransport]] + _transport_registry["grpc"] = StreamsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = StreamsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = StreamsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[StreamsServiceTransport]: + """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 StreamsServiceClient(metaclass=StreamsServiceClientMeta): + """Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + StreamsServiceClient: 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: + StreamsServiceClient: 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) -> StreamsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def channel_path(project: str,location: str,cluster: str,channel: str,) -> str: + """Returns a fully-qualified channel string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/channels/{channel}".format(project=project, location=location, cluster=cluster, channel=channel, ) + + @staticmethod + def parse_channel_path(path: str) -> Dict[str,str]: + """Parses a channel path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/channels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def event_path(project: str,location: str,cluster: str,event: str,) -> str: + """Returns a fully-qualified event string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/events/{event}".format(project=project, location=location, cluster=cluster, event=event, ) + + @staticmethod + def parse_event_path(path: str) -> Dict[str,str]: + """Parses a event path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/events/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def series_path(project: str,location: str,cluster: str,series: str,) -> str: + """Returns a fully-qualified series string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + + @staticmethod + def parse_series_path(path: str) -> Dict[str,str]: + """Parses a series path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/series/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def stream_path(project: str,location: str,cluster: str,stream: str,) -> str: + """Returns a fully-qualified stream string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + + @staticmethod + def parse_stream_path(path: str) -> Dict[str,str]: + """Parses a stream path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/streams/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = StreamsServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + StreamsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StreamsServiceTransport, Callable[..., StreamsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streams service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,StreamsServiceTransport,Callable[..., StreamsServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StreamsServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StreamsServiceClient._read_environment_variables() + self._client_cert_source = StreamsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = StreamsServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, StreamsServiceTransport) + if transport_provided: + # transport is a StreamsServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(StreamsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + StreamsServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[StreamsServiceTransport], Callable[..., StreamsServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., StreamsServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_clusters(self, + request: Optional[Union[streams_service.ListClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListClustersPager: + r"""Lists Clusters in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_clusters(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListClustersRequest, dict]): + The request object. Message for requesting list of + Clusters. + parent (str): + Required. Parent value for + ListClustersRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListClustersPager: + Message for response to listing + Clusters. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListClustersRequest): + request = streams_service.ListClustersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_clusters] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListClustersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_cluster(self, + request: Optional[Union[streams_service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetClusterRequest, dict]): + The request object. Message for getting a Cluster. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Cluster: + Message describing the Cluster + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetClusterRequest): + request = streams_service.GetClusterRequest(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_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_cluster(self, + request: Optional[Union[streams_service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[common.Cluster] = None, + cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Cluster in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateClusterRequest, dict]): + The request object. Message for creating a Cluster. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.visionai_v1alpha1.types.Cluster): + Required. The resource being created. + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Cluster` + Message describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, cluster, cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateClusterRequest): + request = streams_service.CreateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_cluster(self, + request: Optional[Union[streams_service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[common.Cluster] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateClusterRequest, dict]): + The request object. Message for updating a Cluster. + cluster (google.cloud.visionai_v1alpha1.types.Cluster): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Cluster` + Message describing the Cluster object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateClusterRequest): + request = streams_service.UpdateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster.name", request.cluster.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + common.Cluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_cluster(self, + request: Optional[Union[streams_service.DeleteClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteClusterRequest, dict]): + The request object. Message for deleting a Cluster. + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteClusterRequest): + request = streams_service.DeleteClusterRequest(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_cluster] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_streams(self, + request: Optional[Union[streams_service.ListStreamsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListStreamsPager: + r"""Lists Streams in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_streams(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListStreamsRequest, dict]): + The request object. Message for requesting list of + Streams. + parent (str): + Required. Parent value for + ListStreamsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListStreamsPager: + Message for response to listing + Streams. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListStreamsRequest): + request = streams_service.ListStreamsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_streams] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListStreamsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_stream(self, + request: Optional[Union[streams_service.GetStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Stream: + r"""Gets details of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = client.get_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetStreamRequest, dict]): + The request object. Message for getting a Stream. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Stream: + Message describing the Stream object. + The Stream and the Event resources are + many to many; i.e., each Stream resource + can associate to many Event resources + and each Event resource can associate to + many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetStreamRequest): + request = streams_service.GetStreamRequest(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_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_stream(self, + request: Optional[Union[streams_service.CreateStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + stream: Optional[streams_resources.Stream] = None, + stream_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Stream in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateStreamRequest, dict]): + The request object. Message for creating a Stream. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream (google.cloud.visionai_v1alpha1.types.Stream): + Required. The resource being created. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``stream_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, stream, stream_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateStreamRequest): + request = streams_service.CreateStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if stream is not None: + request.stream = stream + if stream_id is not None: + request.stream_id = stream_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_stream(self, + request: Optional[Union[streams_service.UpdateStreamRequest, dict]] = None, + *, + stream: Optional[streams_resources.Stream] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateStreamRequest, dict]): + The request object. Message for updating a Stream. + stream (google.cloud.visionai_v1alpha1.types.Stream): + Required. The resource being updated. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Stream resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Stream` Message describing the Stream object. The Stream and the Event resources are + many to many; i.e., each Stream resource can + associate to many Event resources and each Event + resource can associate to many Stream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateStreamRequest): + request = streams_service.UpdateStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + 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_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream.name", request.stream.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Stream, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_stream(self, + request: Optional[Union[streams_service.DeleteStreamRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Stream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteStreamRequest, dict]): + The request object. Message for deleting a Stream. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteStreamRequest): + request = streams_service.DeleteStreamRequest(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_stream] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_stream_hls_token(self, + request: Optional[Union[streams_service.GenerateStreamHlsTokenRequest, dict]] = None, + *, + stream: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_service.GenerateStreamHlsTokenResponse: + r"""Generate the JWT auth token required to get the + stream HLS contents. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenRequest, dict]): + The request object. Request message for getting the auth + token to access the stream HLS contents. + stream (str): + Required. The name of the stream. + This corresponds to the ``stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenResponse: + Response message for + GenerateStreamHlsToken. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([stream]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GenerateStreamHlsTokenRequest): + request = streams_service.GenerateStreamHlsTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if stream is not None: + request.stream = stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_stream_hls_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("stream", request.stream), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_events(self, + request: Optional[Union[streams_service.ListEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEventsPager: + r"""Lists Events in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_events(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListEventsRequest, dict]): + The request object. Message for requesting list of + Events. + parent (str): + Required. Parent value for + ListEventsRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListEventsPager: + Message for response to listing + Events. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListEventsRequest): + request = streams_service.ListEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_events] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListEventsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_event(self, + request: Optional[Union[streams_service.GetEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Event: + r"""Gets details of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetEventRequest, dict]): + The request object. Message for getting a Event. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Event: + Message describing the Event object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetEventRequest): + request = streams_service.GetEventRequest(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_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_event(self, + request: Optional[Union[streams_service.CreateEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + event: Optional[streams_resources.Event] = None, + event_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Event in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateEventRequest, dict]): + The request object. Message for creating a Event. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event (google.cloud.visionai_v1alpha1.types.Event): + Required. The resource being created. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``event_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Event` + Message describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event, event_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateEventRequest): + request = streams_service.CreateEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event is not None: + request.event = event + if event_id is not None: + request.event_id = event_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_event(self, + request: Optional[Union[streams_service.UpdateEventRequest, dict]] = None, + *, + event: Optional[streams_resources.Event] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateEventRequest, dict]): + The request object. Message for updating a Event. + event (google.cloud.visionai_v1alpha1.types.Event): + Required. The resource being updated. + This corresponds to the ``event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Event resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Event` + Message describing the Event object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateEventRequest): + request = streams_service.UpdateEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event is not None: + request.event = event + 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_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event.name", request.event.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Event, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_event(self, + request: Optional[Union[streams_service.DeleteEventRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteEventRequest, dict]): + The request object. Message for deleting a Event. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteEventRequest): + request = streams_service.DeleteEventRequest(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_event] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_series(self, + request: Optional[Union[streams_service.ListSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSeriesPager: + r"""Lists Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListSeriesRequest, dict]): + The request object. Message for requesting list of + Series. + parent (str): + Required. Parent value for + ListSeriesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListSeriesPager: + Message for response to listing + Series. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.ListSeriesRequest): + request = streams_service.ListSeriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListSeriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_series(self, + request: Optional[Union[streams_service.GetSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> streams_resources.Series: + r"""Gets details of a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = client.get_series(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetSeriesRequest, dict]): + The request object. Message for getting a Series. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Series: + Message describing the Series object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.GetSeriesRequest): + request = streams_service.GetSeriesRequest(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_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_series(self, + request: Optional[Union[streams_service.CreateSeriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + series: Optional[streams_resources.Series] = None, + series_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new Series in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateSeriesRequest, dict]): + The request object. Message for creating a Series. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series (google.cloud.visionai_v1alpha1.types.Series): + Required. The resource being created. + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + series_id (str): + Required. Id of the requesting + object. + + This corresponds to the ``series_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Series` + Message describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, series, series_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.CreateSeriesRequest): + request = streams_service.CreateSeriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if series is not None: + request.series = series + if series_id is not None: + request.series_id = series_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_series(self, + request: Optional[Union[streams_service.UpdateSeriesRequest, dict]] = None, + *, + series: Optional[streams_resources.Series] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateSeriesRequest, dict]): + The request object. Message for updating a Series. + series (google.cloud.visionai_v1alpha1.types.Series): + Required. The resource being updated + This corresponds to the ``series`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Series resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Series` + Message describing the Series object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([series, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.UpdateSeriesRequest): + request = streams_service.UpdateSeriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if series is not None: + request.series = series + 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_series] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("series.name", request.series.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Series, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_series(self, + request: Optional[Union[streams_service.DeleteSeriesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single Series. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteSeriesRequest, dict]): + The request object. Message for deleting a Series. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.DeleteSeriesRequest): + request = streams_service.DeleteSeriesRequest(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_series] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def materialize_channel(self, + request: Optional[Union[streams_service.MaterializeChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[streams_resources.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Materialize a channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_materialize_channel(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + channel = visionai_v1alpha1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1alpha1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.MaterializeChannelRequest, dict]): + The request object. Message for materializing a channel. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel (google.cloud.visionai_v1alpha1.types.Channel): + Required. The resource being created. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_id (str): + Required. Id of the channel. + This corresponds to the ``channel_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.visionai_v1alpha1.types.Channel` + Message describing the Channel object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel, channel_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, streams_service.MaterializeChannelRequest): + request = streams_service.MaterializeChannelRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel is not None: + request.channel = channel + if channel_id is not None: + request.channel_id = channel_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.materialize_channel] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + streams_resources.Channel, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "StreamsServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StreamsServiceClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/pagers.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/pagers.py new file mode 100644 index 000000000000..5565b5c27de7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/pagers.py @@ -0,0 +1,504 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service + + +class ListClustersPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListClustersResponse` + 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[..., streams_service.ListClustersResponse], + request: streams_service.ListClustersRequest, + response: streams_service.ListClustersResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListClustersRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListClustersResponse): + 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 = streams_service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[common.Cluster]: + for page in self.pages: + yield from page.clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClustersAsyncPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListClustersResponse` + 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[streams_service.ListClustersResponse]], + request: streams_service.ListClustersRequest, + response: streams_service.ListClustersResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListClustersRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListClustersResponse): + 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 = streams_service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[common.Cluster]: + async def async_generator(): + async for page in self.pages: + for response in page.clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListStreamsPager: + """A pager for iterating through ``list_streams`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListStreamsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``streams`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListStreams`` requests and continue to iterate + through the ``streams`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListStreamsResponse` + 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[..., streams_service.ListStreamsResponse], + request: streams_service.ListStreamsRequest, + response: streams_service.ListStreamsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListStreamsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListStreamsResponse): + 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 = streams_service.ListStreamsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListStreamsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[streams_resources.Stream]: + for page in self.pages: + yield from page.streams + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListStreamsAsyncPager: + """A pager for iterating through ``list_streams`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListStreamsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``streams`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListStreams`` requests and continue to iterate + through the ``streams`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListStreamsResponse` + 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[streams_service.ListStreamsResponse]], + request: streams_service.ListStreamsRequest, + response: streams_service.ListStreamsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListStreamsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListStreamsResponse): + 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 = streams_service.ListStreamsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListStreamsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[streams_resources.Stream]: + async def async_generator(): + async for page in self.pages: + for response in page.streams: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventsPager: + """A pager for iterating through ``list_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvents`` requests and continue to iterate + through the ``events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListEventsResponse` + 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[..., streams_service.ListEventsResponse], + request: streams_service.ListEventsRequest, + response: streams_service.ListEventsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListEventsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListEventsResponse): + 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 = streams_service.ListEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[streams_resources.Event]: + for page in self.pages: + yield from page.events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventsAsyncPager: + """A pager for iterating through ``list_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvents`` requests and continue to iterate + through the ``events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListEventsResponse` + 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[streams_service.ListEventsResponse]], + request: streams_service.ListEventsRequest, + response: streams_service.ListEventsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListEventsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListEventsResponse): + 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 = streams_service.ListEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[streams_resources.Event]: + async def async_generator(): + async for page in self.pages: + for response in page.events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSeriesPager: + """A pager for iterating through ``list_series`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListSeriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``series`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSeries`` requests and continue to iterate + through the ``series`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListSeriesResponse` + 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[..., streams_service.ListSeriesResponse], + request: streams_service.ListSeriesRequest, + response: streams_service.ListSeriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListSeriesRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListSeriesResponse): + 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 = streams_service.ListSeriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[streams_service.ListSeriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[streams_resources.Series]: + for page in self.pages: + yield from page.series + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSeriesAsyncPager: + """A pager for iterating through ``list_series`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListSeriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``series`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSeries`` requests and continue to iterate + through the ``series`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListSeriesResponse` + 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[streams_service.ListSeriesResponse]], + request: streams_service.ListSeriesRequest, + response: streams_service.ListSeriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListSeriesRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListSeriesResponse): + 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 = streams_service.ListSeriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[streams_service.ListSeriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[streams_resources.Series]: + async def async_generator(): + async for page in self.pages: + for response in page.series: + 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/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/__init__.py new file mode 100644 index 000000000000..6fec714da909 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 StreamsServiceTransport +from .grpc import StreamsServiceGrpcTransport +from .grpc_asyncio import StreamsServiceGrpcAsyncIOTransport +from .rest import StreamsServiceRestTransport +from .rest import StreamsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StreamsServiceTransport]] +_transport_registry['grpc'] = StreamsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = StreamsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = StreamsServiceRestTransport + +__all__ = ( + 'StreamsServiceTransport', + 'StreamsServiceGrpcTransport', + 'StreamsServiceGrpcAsyncIOTransport', + 'StreamsServiceRestTransport', + 'StreamsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/base.py new file mode 100644 index 000000000000..ed4cbcbe39ea --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/base.py @@ -0,0 +1,540 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class StreamsServiceTransport(abc.ABC): + """Abstract transport class for StreamsService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_clusters: gapic_v1.method.wrap_method( + self.list_clusters, + default_timeout=None, + client_info=client_info, + ), + self.get_cluster: gapic_v1.method.wrap_method( + self.get_cluster, + default_timeout=None, + client_info=client_info, + ), + self.create_cluster: gapic_v1.method.wrap_method( + self.create_cluster, + default_timeout=None, + client_info=client_info, + ), + self.update_cluster: gapic_v1.method.wrap_method( + self.update_cluster, + default_timeout=None, + client_info=client_info, + ), + self.delete_cluster: gapic_v1.method.wrap_method( + self.delete_cluster, + default_timeout=None, + client_info=client_info, + ), + self.list_streams: gapic_v1.method.wrap_method( + self.list_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_stream: gapic_v1.method.wrap_method( + self.get_stream, + default_timeout=None, + client_info=client_info, + ), + self.create_stream: gapic_v1.method.wrap_method( + self.create_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_stream: gapic_v1.method.wrap_method( + self.update_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_stream: gapic_v1.method.wrap_method( + self.delete_stream, + default_timeout=None, + client_info=client_info, + ), + self.generate_stream_hls_token: gapic_v1.method.wrap_method( + self.generate_stream_hls_token, + default_timeout=None, + client_info=client_info, + ), + self.list_events: gapic_v1.method.wrap_method( + self.list_events, + default_timeout=None, + client_info=client_info, + ), + self.get_event: gapic_v1.method.wrap_method( + self.get_event, + default_timeout=None, + client_info=client_info, + ), + self.create_event: gapic_v1.method.wrap_method( + self.create_event, + default_timeout=None, + client_info=client_info, + ), + self.update_event: gapic_v1.method.wrap_method( + self.update_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_event: gapic_v1.method.wrap_method( + self.delete_event, + default_timeout=None, + client_info=client_info, + ), + self.list_series: gapic_v1.method.wrap_method( + self.list_series, + default_timeout=None, + client_info=client_info, + ), + self.get_series: gapic_v1.method.wrap_method( + self.get_series, + default_timeout=None, + client_info=client_info, + ), + self.create_series: gapic_v1.method.wrap_method( + self.create_series, + default_timeout=None, + client_info=client_info, + ), + self.update_series: gapic_v1.method.wrap_method( + self.update_series, + default_timeout=None, + client_info=client_info, + ), + self.delete_series: gapic_v1.method.wrap_method( + self.delete_series, + default_timeout=None, + client_info=client_info, + ), + self.materialize_channel: gapic_v1.method.wrap_method( + self.materialize_channel, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + Union[ + streams_service.ListClustersResponse, + Awaitable[streams_service.ListClustersResponse] + ]]: + raise NotImplementedError() + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + Union[ + common.Cluster, + Awaitable[common.Cluster] + ]]: + raise NotImplementedError() + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + Union[ + streams_service.ListStreamsResponse, + Awaitable[streams_service.ListStreamsResponse] + ]]: + raise NotImplementedError() + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + Union[ + streams_resources.Stream, + Awaitable[streams_resources.Stream] + ]]: + raise NotImplementedError() + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + Union[ + streams_service.GenerateStreamHlsTokenResponse, + Awaitable[streams_service.GenerateStreamHlsTokenResponse] + ]]: + raise NotImplementedError() + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + Union[ + streams_service.ListEventsResponse, + Awaitable[streams_service.ListEventsResponse] + ]]: + raise NotImplementedError() + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + Union[ + streams_resources.Event, + Awaitable[streams_resources.Event] + ]]: + raise NotImplementedError() + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + Union[ + streams_service.ListSeriesResponse, + Awaitable[streams_service.ListSeriesResponse] + ]]: + raise NotImplementedError() + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + Union[ + streams_resources.Series, + Awaitable[streams_resources.Series] + ]]: + raise NotImplementedError() + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'StreamsServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/grpc.py new file mode 100644 index 000000000000..a74f5052b571 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/grpc.py @@ -0,0 +1,1032 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamsServiceTransport, DEFAULT_CLIENT_INFO + + +class StreamsServiceGrpcTransport(StreamsServiceTransport): + """gRPC backend transport for StreamsService. + + Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + streams_service.ListClustersResponse]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + ~.ListClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListClusters', + request_serializer=streams_service.ListClustersRequest.serialize, + response_deserializer=streams_service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + common.Cluster]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + ~.Cluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetCluster', + request_serializer=streams_service.GetClusterRequest.serialize, + response_deserializer=common.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateCluster', + request_serializer=streams_service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateCluster', + request_serializer=streams_service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteCluster', + request_serializer=streams_service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + streams_service.ListStreamsResponse]: + r"""Return a callable for the list streams method over gRPC. + + Lists Streams in a given project and location. + + Returns: + Callable[[~.ListStreamsRequest], + ~.ListStreamsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_streams' not in self._stubs: + self._stubs['list_streams'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListStreams', + request_serializer=streams_service.ListStreamsRequest.serialize, + response_deserializer=streams_service.ListStreamsResponse.deserialize, + ) + return self._stubs['list_streams'] + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + streams_resources.Stream]: + r"""Return a callable for the get stream method over gRPC. + + Gets details of a single Stream. + + Returns: + Callable[[~.GetStreamRequest], + ~.Stream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_stream' not in self._stubs: + self._stubs['get_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetStream', + request_serializer=streams_service.GetStreamRequest.serialize, + response_deserializer=streams_resources.Stream.deserialize, + ) + return self._stubs['get_stream'] + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + operations_pb2.Operation]: + r"""Return a callable for the create stream method over gRPC. + + Creates a new Stream in a given project and location. + + Returns: + Callable[[~.CreateStreamRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_stream' not in self._stubs: + self._stubs['create_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateStream', + request_serializer=streams_service.CreateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_stream'] + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + operations_pb2.Operation]: + r"""Return a callable for the update stream method over gRPC. + + Updates the parameters of a single Stream. + + Returns: + Callable[[~.UpdateStreamRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_stream' not in self._stubs: + self._stubs['update_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateStream', + request_serializer=streams_service.UpdateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_stream'] + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete stream method over gRPC. + + Deletes a single Stream. + + Returns: + Callable[[~.DeleteStreamRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_stream' not in self._stubs: + self._stubs['delete_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteStream', + request_serializer=streams_service.DeleteStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_stream'] + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + streams_service.GenerateStreamHlsTokenResponse]: + r"""Return a callable for the generate stream hls token method over gRPC. + + Generate the JWT auth token required to get the + stream HLS contents. + + Returns: + Callable[[~.GenerateStreamHlsTokenRequest], + ~.GenerateStreamHlsTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_stream_hls_token' not in self._stubs: + self._stubs['generate_stream_hls_token'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GenerateStreamHlsToken', + request_serializer=streams_service.GenerateStreamHlsTokenRequest.serialize, + response_deserializer=streams_service.GenerateStreamHlsTokenResponse.deserialize, + ) + return self._stubs['generate_stream_hls_token'] + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + streams_service.ListEventsResponse]: + r"""Return a callable for the list events method over gRPC. + + Lists Events in a given project and location. + + Returns: + Callable[[~.ListEventsRequest], + ~.ListEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_events' not in self._stubs: + self._stubs['list_events'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListEvents', + request_serializer=streams_service.ListEventsRequest.serialize, + response_deserializer=streams_service.ListEventsResponse.deserialize, + ) + return self._stubs['list_events'] + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + streams_resources.Event]: + r"""Return a callable for the get event method over gRPC. + + Gets details of a single Event. + + Returns: + Callable[[~.GetEventRequest], + ~.Event]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event' not in self._stubs: + self._stubs['get_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetEvent', + request_serializer=streams_service.GetEventRequest.serialize, + response_deserializer=streams_resources.Event.deserialize, + ) + return self._stubs['get_event'] + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + operations_pb2.Operation]: + r"""Return a callable for the create event method over gRPC. + + Creates a new Event in a given project and location. + + Returns: + Callable[[~.CreateEventRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event' not in self._stubs: + self._stubs['create_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateEvent', + request_serializer=streams_service.CreateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_event'] + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + operations_pb2.Operation]: + r"""Return a callable for the update event method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateEventRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event' not in self._stubs: + self._stubs['update_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateEvent', + request_serializer=streams_service.UpdateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_event'] + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete event method over gRPC. + + Deletes a single Event. + + Returns: + Callable[[~.DeleteEventRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_event' not in self._stubs: + self._stubs['delete_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteEvent', + request_serializer=streams_service.DeleteEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_event'] + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + streams_service.ListSeriesResponse]: + r"""Return a callable for the list series method over gRPC. + + Lists Series in a given project and location. + + Returns: + Callable[[~.ListSeriesRequest], + ~.ListSeriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['list_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListSeries', + request_serializer=streams_service.ListSeriesRequest.serialize, + response_deserializer=streams_service.ListSeriesResponse.deserialize, + ) + return self._stubs['list_series'] + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + streams_resources.Series]: + r"""Return a callable for the get series method over gRPC. + + Gets details of a single Series. + + Returns: + Callable[[~.GetSeriesRequest], + ~.Series]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['get_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetSeries', + request_serializer=streams_service.GetSeriesRequest.serialize, + response_deserializer=streams_resources.Series.deserialize, + ) + return self._stubs['get_series'] + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the create series method over gRPC. + + Creates a new Series in a given project and location. + + Returns: + Callable[[~.CreateSeriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_series' not in self._stubs: + self._stubs['create_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateSeries', + request_serializer=streams_service.CreateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_series'] + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the update series method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateSeriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_series' not in self._stubs: + self._stubs['update_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateSeries', + request_serializer=streams_service.UpdateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_series'] + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete series method over gRPC. + + Deletes a single Series. + + Returns: + Callable[[~.DeleteSeriesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_series' not in self._stubs: + self._stubs['delete_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteSeries', + request_serializer=streams_service.DeleteSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_series'] + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + operations_pb2.Operation]: + r"""Return a callable for the materialize channel method over gRPC. + + Materialize a channel. + + Returns: + Callable[[~.MaterializeChannelRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'materialize_channel' not in self._stubs: + self._stubs['materialize_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/MaterializeChannel', + request_serializer=streams_service.MaterializeChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['materialize_channel'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'StreamsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..973506436983 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/grpc_asyncio.py @@ -0,0 +1,1147 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import StreamsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import StreamsServiceGrpcTransport + + +class StreamsServiceGrpcAsyncIOTransport(StreamsServiceTransport): + """gRPC AsyncIO backend transport for StreamsService. + + Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + Awaitable[streams_service.ListClustersResponse]]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + Awaitable[~.ListClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListClusters', + request_serializer=streams_service.ListClustersRequest.serialize, + response_deserializer=streams_service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + Awaitable[common.Cluster]]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + Awaitable[~.Cluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetCluster', + request_serializer=streams_service.GetClusterRequest.serialize, + response_deserializer=common.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateCluster', + request_serializer=streams_service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateCluster', + request_serializer=streams_service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteCluster', + request_serializer=streams_service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + Awaitable[streams_service.ListStreamsResponse]]: + r"""Return a callable for the list streams method over gRPC. + + Lists Streams in a given project and location. + + Returns: + Callable[[~.ListStreamsRequest], + Awaitable[~.ListStreamsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_streams' not in self._stubs: + self._stubs['list_streams'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListStreams', + request_serializer=streams_service.ListStreamsRequest.serialize, + response_deserializer=streams_service.ListStreamsResponse.deserialize, + ) + return self._stubs['list_streams'] + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + Awaitable[streams_resources.Stream]]: + r"""Return a callable for the get stream method over gRPC. + + Gets details of a single Stream. + + Returns: + Callable[[~.GetStreamRequest], + Awaitable[~.Stream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_stream' not in self._stubs: + self._stubs['get_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetStream', + request_serializer=streams_service.GetStreamRequest.serialize, + response_deserializer=streams_resources.Stream.deserialize, + ) + return self._stubs['get_stream'] + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create stream method over gRPC. + + Creates a new Stream in a given project and location. + + Returns: + Callable[[~.CreateStreamRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_stream' not in self._stubs: + self._stubs['create_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateStream', + request_serializer=streams_service.CreateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_stream'] + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update stream method over gRPC. + + Updates the parameters of a single Stream. + + Returns: + Callable[[~.UpdateStreamRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_stream' not in self._stubs: + self._stubs['update_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateStream', + request_serializer=streams_service.UpdateStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_stream'] + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete stream method over gRPC. + + Deletes a single Stream. + + Returns: + Callable[[~.DeleteStreamRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_stream' not in self._stubs: + self._stubs['delete_stream'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteStream', + request_serializer=streams_service.DeleteStreamRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_stream'] + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + Awaitable[streams_service.GenerateStreamHlsTokenResponse]]: + r"""Return a callable for the generate stream hls token method over gRPC. + + Generate the JWT auth token required to get the + stream HLS contents. + + Returns: + Callable[[~.GenerateStreamHlsTokenRequest], + Awaitable[~.GenerateStreamHlsTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_stream_hls_token' not in self._stubs: + self._stubs['generate_stream_hls_token'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GenerateStreamHlsToken', + request_serializer=streams_service.GenerateStreamHlsTokenRequest.serialize, + response_deserializer=streams_service.GenerateStreamHlsTokenResponse.deserialize, + ) + return self._stubs['generate_stream_hls_token'] + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + Awaitable[streams_service.ListEventsResponse]]: + r"""Return a callable for the list events method over gRPC. + + Lists Events in a given project and location. + + Returns: + Callable[[~.ListEventsRequest], + Awaitable[~.ListEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_events' not in self._stubs: + self._stubs['list_events'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListEvents', + request_serializer=streams_service.ListEventsRequest.serialize, + response_deserializer=streams_service.ListEventsResponse.deserialize, + ) + return self._stubs['list_events'] + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + Awaitable[streams_resources.Event]]: + r"""Return a callable for the get event method over gRPC. + + Gets details of a single Event. + + Returns: + Callable[[~.GetEventRequest], + Awaitable[~.Event]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event' not in self._stubs: + self._stubs['get_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetEvent', + request_serializer=streams_service.GetEventRequest.serialize, + response_deserializer=streams_resources.Event.deserialize, + ) + return self._stubs['get_event'] + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create event method over gRPC. + + Creates a new Event in a given project and location. + + Returns: + Callable[[~.CreateEventRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event' not in self._stubs: + self._stubs['create_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateEvent', + request_serializer=streams_service.CreateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_event'] + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update event method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateEventRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event' not in self._stubs: + self._stubs['update_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateEvent', + request_serializer=streams_service.UpdateEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_event'] + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete event method over gRPC. + + Deletes a single Event. + + Returns: + Callable[[~.DeleteEventRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_event' not in self._stubs: + self._stubs['delete_event'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteEvent', + request_serializer=streams_service.DeleteEventRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_event'] + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + Awaitable[streams_service.ListSeriesResponse]]: + r"""Return a callable for the list series method over gRPC. + + Lists Series in a given project and location. + + Returns: + Callable[[~.ListSeriesRequest], + Awaitable[~.ListSeriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['list_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/ListSeries', + request_serializer=streams_service.ListSeriesRequest.serialize, + response_deserializer=streams_service.ListSeriesResponse.deserialize, + ) + return self._stubs['list_series'] + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + Awaitable[streams_resources.Series]]: + r"""Return a callable for the get series method over gRPC. + + Gets details of a single Series. + + Returns: + Callable[[~.GetSeriesRequest], + Awaitable[~.Series]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_series' not in self._stubs: + self._stubs['get_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/GetSeries', + request_serializer=streams_service.GetSeriesRequest.serialize, + response_deserializer=streams_resources.Series.deserialize, + ) + return self._stubs['get_series'] + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create series method over gRPC. + + Creates a new Series in a given project and location. + + Returns: + Callable[[~.CreateSeriesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_series' not in self._stubs: + self._stubs['create_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/CreateSeries', + request_serializer=streams_service.CreateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_series'] + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update series method over gRPC. + + Updates the parameters of a single Event. + + Returns: + Callable[[~.UpdateSeriesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_series' not in self._stubs: + self._stubs['update_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/UpdateSeries', + request_serializer=streams_service.UpdateSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_series'] + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete series method over gRPC. + + Deletes a single Series. + + Returns: + Callable[[~.DeleteSeriesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_series' not in self._stubs: + self._stubs['delete_series'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/DeleteSeries', + request_serializer=streams_service.DeleteSeriesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_series'] + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the materialize channel method over gRPC. + + Materialize a channel. + + Returns: + Callable[[~.MaterializeChannelRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'materialize_channel' not in self._stubs: + self._stubs['materialize_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.StreamsService/MaterializeChannel', + request_serializer=streams_service.MaterializeChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['materialize_channel'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_clusters: gapic_v1.method_async.wrap_method( + self.list_clusters, + default_timeout=None, + client_info=client_info, + ), + self.get_cluster: gapic_v1.method_async.wrap_method( + self.get_cluster, + default_timeout=None, + client_info=client_info, + ), + self.create_cluster: gapic_v1.method_async.wrap_method( + self.create_cluster, + default_timeout=None, + client_info=client_info, + ), + self.update_cluster: gapic_v1.method_async.wrap_method( + self.update_cluster, + default_timeout=None, + client_info=client_info, + ), + self.delete_cluster: gapic_v1.method_async.wrap_method( + self.delete_cluster, + default_timeout=None, + client_info=client_info, + ), + self.list_streams: gapic_v1.method_async.wrap_method( + self.list_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_stream: gapic_v1.method_async.wrap_method( + self.get_stream, + default_timeout=None, + client_info=client_info, + ), + self.create_stream: gapic_v1.method_async.wrap_method( + self.create_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_stream: gapic_v1.method_async.wrap_method( + self.update_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_stream: gapic_v1.method_async.wrap_method( + self.delete_stream, + default_timeout=None, + client_info=client_info, + ), + self.generate_stream_hls_token: gapic_v1.method_async.wrap_method( + self.generate_stream_hls_token, + default_timeout=None, + client_info=client_info, + ), + self.list_events: gapic_v1.method_async.wrap_method( + self.list_events, + default_timeout=None, + client_info=client_info, + ), + self.get_event: gapic_v1.method_async.wrap_method( + self.get_event, + default_timeout=None, + client_info=client_info, + ), + self.create_event: gapic_v1.method_async.wrap_method( + self.create_event, + default_timeout=None, + client_info=client_info, + ), + self.update_event: gapic_v1.method_async.wrap_method( + self.update_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_event: gapic_v1.method_async.wrap_method( + self.delete_event, + default_timeout=None, + client_info=client_info, + ), + self.list_series: gapic_v1.method_async.wrap_method( + self.list_series, + default_timeout=None, + client_info=client_info, + ), + self.get_series: gapic_v1.method_async.wrap_method( + self.get_series, + default_timeout=None, + client_info=client_info, + ), + self.create_series: gapic_v1.method_async.wrap_method( + self.create_series, + default_timeout=None, + client_info=client_info, + ), + self.update_series: gapic_v1.method_async.wrap_method( + self.update_series, + default_timeout=None, + client_info=client_info, + ), + self.delete_series: gapic_v1.method_async.wrap_method( + self.delete_series, + default_timeout=None, + client_info=client_info, + ), + self.materialize_channel: gapic_v1.method_async.wrap_method( + self.materialize_channel, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'StreamsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/rest.py new file mode 100644 index 000000000000..6f2baec57a4d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/streams_service/transports/rest.py @@ -0,0 +1,3617 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import StreamsServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class StreamsServiceRestInterceptor: + """Interceptor for StreamsService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the StreamsServiceRestTransport. + + .. code-block:: python + class MyCustomStreamsServiceInterceptor(StreamsServiceRestInterceptor): + def pre_create_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_stream_hls_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_stream_hls_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_streams(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_streams(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_materialize_channel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_materialize_channel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_series(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_series(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_stream(self, response): + logging.log(f"Received response: {response}") + return response + + transport = StreamsServiceRestTransport(interceptor=MyCustomStreamsServiceInterceptor()) + client = StreamsServiceClient(transport=transport) + + + """ + def pre_create_cluster(self, request: streams_service.CreateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_create_event(self, request: streams_service.CreateEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_event(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_create_series(self, request: streams_service.CreateSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_series(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_create_stream(self, request: streams_service.CreateStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.CreateStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_create_stream(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_cluster(self, request: streams_service.DeleteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_event(self, request: streams_service.DeleteEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_event(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_series(self, request: streams_service.DeleteSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_series(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_stream(self, request: streams_service.DeleteStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.DeleteStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_stream(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_generate_stream_hls_token(self, request: streams_service.GenerateStreamHlsTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GenerateStreamHlsTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_stream_hls_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_generate_stream_hls_token(self, response: streams_service.GenerateStreamHlsTokenResponse) -> streams_service.GenerateStreamHlsTokenResponse: + """Post-rpc interceptor for generate_stream_hls_token + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_cluster(self, request: streams_service.GetClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_cluster(self, response: common.Cluster) -> common.Cluster: + """Post-rpc interceptor for get_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_event(self, request: streams_service.GetEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_event(self, response: streams_resources.Event) -> streams_resources.Event: + """Post-rpc interceptor for get_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_series(self, request: streams_service.GetSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_series(self, response: streams_resources.Series) -> streams_resources.Series: + """Post-rpc interceptor for get_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_stream(self, request: streams_service.GetStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.GetStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_stream(self, response: streams_resources.Stream) -> streams_resources.Stream: + """Post-rpc interceptor for get_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_clusters(self, request: streams_service.ListClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_clusters(self, response: streams_service.ListClustersResponse) -> streams_service.ListClustersResponse: + """Post-rpc interceptor for list_clusters + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_events(self, request: streams_service.ListEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_events(self, response: streams_service.ListEventsResponse) -> streams_service.ListEventsResponse: + """Post-rpc interceptor for list_events + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_series(self, request: streams_service.ListSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_series(self, response: streams_service.ListSeriesResponse) -> streams_service.ListSeriesResponse: + """Post-rpc interceptor for list_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_streams(self, request: streams_service.ListStreamsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.ListStreamsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_streams + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_streams(self, response: streams_service.ListStreamsResponse) -> streams_service.ListStreamsResponse: + """Post-rpc interceptor for list_streams + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_materialize_channel(self, request: streams_service.MaterializeChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.MaterializeChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for materialize_channel + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_materialize_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for materialize_channel + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_cluster(self, request: streams_service.UpdateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_cluster + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_event(self, request: streams_service.UpdateEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_event(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_event + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_series(self, request: streams_service.UpdateSeriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateSeriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_series + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_series(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_series + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_update_stream(self, request: streams_service.UpdateStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[streams_service.UpdateStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_update_stream(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_stream + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the StreamsService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the StreamsService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class StreamsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: StreamsServiceRestInterceptor + + +class StreamsServiceRestTransport(StreamsServiceTransport): + """REST backend transport for StreamsService. + + Service describing handlers for resources. + Vision API and Vision AI API are two independent APIs developed + by the same team. Vision API is for people to annotate their + image while Vision AI is an e2e solution for customer to build + their own computer vision application. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[StreamsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or StreamsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create cluster method over HTTP. + + Args: + request (~.streams_service.CreateClusterRequest): + The request object. Message for creating a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/clusters', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_cluster(request, metadata) + pb_request = streams_service.CreateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_cluster(resp) + return resp + + class _CreateEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "eventId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create event method over HTTP. + + Args: + request (~.streams_service.CreateEventRequest): + The request object. Message for creating a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/events', + 'body': 'event', + }, + ] + request, metadata = self._interceptor.pre_create_event(request, metadata) + pb_request = streams_service.CreateEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_event(resp) + return resp + + class _CreateSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "seriesId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create series method over HTTP. + + Args: + request (~.streams_service.CreateSeriesRequest): + The request object. Message for creating a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/series', + 'body': 'series', + }, + ] + request, metadata = self._interceptor.pre_create_series(request, metadata) + pb_request = streams_service.CreateSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_series(resp) + return resp + + class _CreateStream(StreamsServiceRestStub): + def __hash__(self): + return hash("CreateStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "streamId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.CreateStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create stream method over HTTP. + + Args: + request (~.streams_service.CreateStreamRequest): + The request object. Message for creating a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/streams', + 'body': 'stream', + }, + ] + request, metadata = self._interceptor.pre_create_stream(request, metadata) + pb_request = streams_service.CreateStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_stream(resp) + return resp + + class _DeleteCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete cluster method over HTTP. + + Args: + request (~.streams_service.DeleteClusterRequest): + The request object. Message for deleting a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_cluster(request, metadata) + pb_request = streams_service.DeleteClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_cluster(resp) + return resp + + class _DeleteEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete event method over HTTP. + + Args: + request (~.streams_service.DeleteEventRequest): + The request object. Message for deleting a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/events/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_event(request, metadata) + pb_request = streams_service.DeleteEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_event(resp) + return resp + + class _DeleteSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete series method over HTTP. + + Args: + request (~.streams_service.DeleteSeriesRequest): + The request object. Message for deleting a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/series/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_series(request, metadata) + pb_request = streams_service.DeleteSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_series(resp) + return resp + + class _DeleteStream(StreamsServiceRestStub): + def __hash__(self): + return hash("DeleteStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.DeleteStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete stream method over HTTP. + + Args: + request (~.streams_service.DeleteStreamRequest): + The request object. Message for deleting a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/streams/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_stream(request, metadata) + pb_request = streams_service.DeleteStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_stream(resp) + return resp + + class _GenerateStreamHlsToken(StreamsServiceRestStub): + def __hash__(self): + return hash("GenerateStreamHlsToken") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GenerateStreamHlsTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.GenerateStreamHlsTokenResponse: + r"""Call the generate stream hls token method over HTTP. + + Args: + request (~.streams_service.GenerateStreamHlsTokenRequest): + The request object. Request message for getting the auth + token to access the stream HLS contents. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.GenerateStreamHlsTokenResponse: + Response message for + GenerateStreamHlsToken. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{stream=projects/*/locations/*/clusters/*/streams/*}:generateStreamHlsToken', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_stream_hls_token(request, metadata) + pb_request = streams_service.GenerateStreamHlsTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.GenerateStreamHlsTokenResponse() + pb_resp = streams_service.GenerateStreamHlsTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_stream_hls_token(resp) + return resp + + class _GetCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("GetCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> common.Cluster: + r"""Call the get cluster method over HTTP. + + Args: + request (~.streams_service.GetClusterRequest): + The request object. Message for getting a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.Cluster: + Message describing the Cluster + object. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_cluster(request, metadata) + pb_request = streams_service.GetClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.Cluster() + pb_resp = common.Cluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_cluster(resp) + return resp + + class _GetEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("GetEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_resources.Event: + r"""Call the get event method over HTTP. + + Args: + request (~.streams_service.GetEventRequest): + The request object. Message for getting a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_resources.Event: + Message describing the Event object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/events/*}', + }, + ] + request, metadata = self._interceptor.pre_get_event(request, metadata) + pb_request = streams_service.GetEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_resources.Event() + pb_resp = streams_resources.Event.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_event(resp) + return resp + + class _GetSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("GetSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_resources.Series: + r"""Call the get series method over HTTP. + + Args: + request (~.streams_service.GetSeriesRequest): + The request object. Message for getting a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_resources.Series: + Message describing the Series object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/series/*}', + }, + ] + request, metadata = self._interceptor.pre_get_series(request, metadata) + pb_request = streams_service.GetSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_resources.Series() + pb_resp = streams_resources.Series.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_series(resp) + return resp + + class _GetStream(StreamsServiceRestStub): + def __hash__(self): + return hash("GetStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.GetStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_resources.Stream: + r"""Call the get stream method over HTTP. + + Args: + request (~.streams_service.GetStreamRequest): + The request object. Message for getting a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_resources.Stream: + Message describing the Stream object. + The Stream and the Event resources are + many to many; i.e., each Stream resource + can associate to many Event resources + and each Event resource can associate to + many Stream resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clusters/*/streams/*}', + }, + ] + request, metadata = self._interceptor.pre_get_stream(request, metadata) + pb_request = streams_service.GetStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_resources.Stream() + pb_resp = streams_resources.Stream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_stream(resp) + return resp + + class _ListClusters(StreamsServiceRestStub): + def __hash__(self): + return hash("ListClusters") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListClustersResponse: + r"""Call the list clusters method over HTTP. + + Args: + request (~.streams_service.ListClustersRequest): + The request object. Message for requesting list of + Clusters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListClustersResponse: + Message for response to listing + Clusters. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/clusters', + }, + ] + request, metadata = self._interceptor.pre_list_clusters(request, metadata) + pb_request = streams_service.ListClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListClustersResponse() + pb_resp = streams_service.ListClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_clusters(resp) + return resp + + class _ListEvents(StreamsServiceRestStub): + def __hash__(self): + return hash("ListEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListEventsResponse: + r"""Call the list events method over HTTP. + + Args: + request (~.streams_service.ListEventsRequest): + The request object. Message for requesting list of + Events. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListEventsResponse: + Message for response to listing + Events. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/events', + }, + ] + request, metadata = self._interceptor.pre_list_events(request, metadata) + pb_request = streams_service.ListEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListEventsResponse() + pb_resp = streams_service.ListEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_events(resp) + return resp + + class _ListSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("ListSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListSeriesResponse: + r"""Call the list series method over HTTP. + + Args: + request (~.streams_service.ListSeriesRequest): + The request object. Message for requesting list of + Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListSeriesResponse: + Message for response to listing + Series. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/series', + }, + ] + request, metadata = self._interceptor.pre_list_series(request, metadata) + pb_request = streams_service.ListSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListSeriesResponse() + pb_resp = streams_service.ListSeriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_series(resp) + return resp + + class _ListStreams(StreamsServiceRestStub): + def __hash__(self): + return hash("ListStreams") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.ListStreamsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> streams_service.ListStreamsResponse: + r"""Call the list streams method over HTTP. + + Args: + request (~.streams_service.ListStreamsRequest): + The request object. Message for requesting list of + Streams. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.streams_service.ListStreamsResponse: + Message for response to listing + Streams. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/streams', + }, + ] + request, metadata = self._interceptor.pre_list_streams(request, metadata) + pb_request = streams_service.ListStreamsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = streams_service.ListStreamsResponse() + pb_resp = streams_service.ListStreamsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_streams(resp) + return resp + + class _MaterializeChannel(StreamsServiceRestStub): + def __hash__(self): + return hash("MaterializeChannel") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "channelId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.MaterializeChannelRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the materialize channel method over HTTP. + + Args: + request (~.streams_service.MaterializeChannelRequest): + The request object. Message for materializing a channel. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/clusters/*}/channels', + 'body': 'channel', + }, + ] + request, metadata = self._interceptor.pre_materialize_channel(request, metadata) + pb_request = streams_service.MaterializeChannelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_materialize_channel(resp) + return resp + + class _UpdateCluster(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update cluster method over HTTP. + + Args: + request (~.streams_service.UpdateClusterRequest): + The request object. Message for updating a Cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{cluster.name=projects/*/locations/*/clusters/*}', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_update_cluster(request, metadata) + pb_request = streams_service.UpdateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_cluster(resp) + return resp + + class _UpdateEvent(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update event method over HTTP. + + Args: + request (~.streams_service.UpdateEventRequest): + The request object. Message for updating a Event. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{event.name=projects/*/locations/*/clusters/*/events/*}', + 'body': 'event', + }, + ] + request, metadata = self._interceptor.pre_update_event(request, metadata) + pb_request = streams_service.UpdateEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_event(resp) + return resp + + class _UpdateSeries(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateSeries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateSeriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update series method over HTTP. + + Args: + request (~.streams_service.UpdateSeriesRequest): + The request object. Message for updating a Series. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{series.name=projects/*/locations/*/clusters/*/series/*}', + 'body': 'series', + }, + ] + request, metadata = self._interceptor.pre_update_series(request, metadata) + pb_request = streams_service.UpdateSeriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_series(resp) + return resp + + class _UpdateStream(StreamsServiceRestStub): + def __hash__(self): + return hash("UpdateStream") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: streams_service.UpdateStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update stream method over HTTP. + + Args: + request (~.streams_service.UpdateStreamRequest): + The request object. Message for updating a Stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{stream.name=projects/*/locations/*/clusters/*/streams/*}', + 'body': 'stream', + }, + ] + request, metadata = self._interceptor.pre_update_stream(request, metadata) + pb_request = streams_service.UpdateStreamRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_stream(resp) + return resp + + @property + def create_cluster(self) -> Callable[ + [streams_service.CreateClusterRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_event(self) -> Callable[ + [streams_service.CreateEventRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_series(self) -> Callable[ + [streams_service.CreateSeriesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_stream(self) -> Callable[ + [streams_service.CreateStreamRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_cluster(self) -> Callable[ + [streams_service.DeleteClusterRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_event(self) -> Callable[ + [streams_service.DeleteEventRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_series(self) -> Callable[ + [streams_service.DeleteSeriesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_stream(self) -> Callable[ + [streams_service.DeleteStreamRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_stream_hls_token(self) -> Callable[ + [streams_service.GenerateStreamHlsTokenRequest], + streams_service.GenerateStreamHlsTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateStreamHlsToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_cluster(self) -> Callable[ + [streams_service.GetClusterRequest], + common.Cluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_event(self) -> Callable[ + [streams_service.GetEventRequest], + streams_resources.Event]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_series(self) -> Callable[ + [streams_service.GetSeriesRequest], + streams_resources.Series]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_stream(self) -> Callable[ + [streams_service.GetStreamRequest], + streams_resources.Stream]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_clusters(self) -> Callable[ + [streams_service.ListClustersRequest], + streams_service.ListClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_events(self) -> Callable[ + [streams_service.ListEventsRequest], + streams_service.ListEventsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_series(self) -> Callable[ + [streams_service.ListSeriesRequest], + streams_service.ListSeriesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_streams(self) -> Callable[ + [streams_service.ListStreamsRequest], + streams_service.ListStreamsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListStreams(self._session, self._host, self._interceptor) # type: ignore + + @property + def materialize_channel(self) -> Callable[ + [streams_service.MaterializeChannelRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._MaterializeChannel(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_cluster(self) -> Callable[ + [streams_service.UpdateClusterRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_event(self) -> Callable[ + [streams_service.UpdateEventRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_series(self) -> Callable[ + [streams_service.UpdateSeriesRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSeries(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_stream(self) -> Callable[ + [streams_service.UpdateStreamRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(StreamsServiceRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(StreamsServiceRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(StreamsServiceRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(StreamsServiceRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(StreamsServiceRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(StreamsServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'StreamsServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/__init__.py new file mode 100644 index 000000000000..3e3bcdf7cf2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 WarehouseClient +from .async_client import WarehouseAsyncClient + +__all__ = ( + 'WarehouseClient', + 'WarehouseAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/async_client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/async_client.py new file mode 100644 index 000000000000..a5c29c6dd235 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/async_client.py @@ -0,0 +1,4063 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.warehouse import pagers +from google.cloud.visionai_v1alpha1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WarehouseTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WarehouseGrpcAsyncIOTransport +from .client import WarehouseClient + + +class WarehouseAsyncClient: + """Service that manages media content + metadata for streaming.""" + + _client: WarehouseClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WarehouseClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WarehouseClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WarehouseClient._DEFAULT_UNIVERSE + + annotation_path = staticmethod(WarehouseClient.annotation_path) + parse_annotation_path = staticmethod(WarehouseClient.parse_annotation_path) + asset_path = staticmethod(WarehouseClient.asset_path) + parse_asset_path = staticmethod(WarehouseClient.parse_asset_path) + corpus_path = staticmethod(WarehouseClient.corpus_path) + parse_corpus_path = staticmethod(WarehouseClient.parse_corpus_path) + data_schema_path = staticmethod(WarehouseClient.data_schema_path) + parse_data_schema_path = staticmethod(WarehouseClient.parse_data_schema_path) + search_config_path = staticmethod(WarehouseClient.search_config_path) + parse_search_config_path = staticmethod(WarehouseClient.parse_search_config_path) + common_billing_account_path = staticmethod(WarehouseClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WarehouseClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WarehouseClient.common_folder_path) + parse_common_folder_path = staticmethod(WarehouseClient.parse_common_folder_path) + common_organization_path = staticmethod(WarehouseClient.common_organization_path) + parse_common_organization_path = staticmethod(WarehouseClient.parse_common_organization_path) + common_project_path = staticmethod(WarehouseClient.common_project_path) + parse_common_project_path = staticmethod(WarehouseClient.parse_common_project_path) + common_location_path = staticmethod(WarehouseClient.common_location_path) + parse_common_location_path = staticmethod(WarehouseClient.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: + WarehouseAsyncClient: The constructed client. + """ + return WarehouseClient.from_service_account_info.__func__(WarehouseAsyncClient, 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: + WarehouseAsyncClient: The constructed client. + """ + return WarehouseClient.from_service_account_file.__func__(WarehouseAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return WarehouseClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WarehouseTransport: + """Returns the transport used by the client instance. + + Returns: + WarehouseTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(WarehouseClient).get_transport_class, type(WarehouseClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WarehouseTransport, Callable[..., WarehouseTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the warehouse async 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 (Optional[Union[str,WarehouseTransport,Callable[..., WarehouseTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the WarehouseTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = WarehouseClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_asset(self, + request: Optional[Union[warehouse.CreateAssetRequest, dict]] = None, + *, + parent: Optional[str] = None, + asset: Optional[warehouse.Asset] = None, + asset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Creates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateAssetRequest, dict]]): + The request object. Request message for + CreateAssetRequest. + parent (:class:`str`): + Required. The parent resource where this asset will be + created. Format: projects/\ */locations/*/corpora/\* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset (:class:`google.cloud.visionai_v1alpha1.types.Asset`): + Required. The asset to create. + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_id (:class:`str`): + Optional. The ID to use for the asset, which will become + the final component of the asset's resource name if user + choose to specify. Otherwise, asset id will be generated + by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``asset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, asset, asset_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAssetRequest): + request = warehouse.CreateAssetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if asset is not None: + request.asset = asset + if asset_id is not None: + request.asset_id = asset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_asset(self, + request: Optional[Union[warehouse.UpdateAssetRequest, dict]] = None, + *, + asset: Optional[warehouse.Asset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Updates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAssetRequest( + ) + + # Make the request + response = await client.update_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateAssetRequest, dict]]): + The request object. Response message for UpdateAsset. + asset (:class:`google.cloud.visionai_v1alpha1.types.Asset`): + Required. The asset to update. + + The asset's ``name`` field is used to identify the asset + to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([asset, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAssetRequest): + request = warehouse.UpdateAssetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if asset is not None: + request.asset = asset + 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._client._transport._wrapped_methods[self._client._transport.update_asset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("asset.name", request.asset.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_asset(self, + request: Optional[Union[warehouse.GetAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Reads an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetAssetRequest, dict]]): + The request object. Request message for GetAsset. + name (:class:`str`): + Required. The name of the asset to retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAssetRequest): + request = warehouse.GetAssetRequest(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._client._transport._wrapped_methods[self._client._transport.get_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[warehouse.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an list of assets inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListAssetsRequest, dict]]): + The request object. Request message for ListAssets. + parent (:class:`str`): + Required. The parent, which owns this collection of + assets. Format: + projects/{project_number}/locations/{location}/corpora/{corpus} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAssetsAsyncPager: + Response message for ListAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAssetsRequest): + request = warehouse.ListAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_assets] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_asset(self, + request: Optional[Union[warehouse.DeleteAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteAssetRequest, dict]]): + The request object. Request message for DeleteAsset. + name (:class:`str`): + Required. The name of the asset to delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAssetRequest): + request = warehouse.DeleteAssetRequest(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._client._transport._wrapped_methods[self._client._transport.delete_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteAssetMetadata, + ) + + # Done; return the response. + return response + + async def create_corpus(self, + request: Optional[Union[warehouse.CreateCorpusRequest, dict]] = None, + *, + parent: Optional[str] = None, + corpus: Optional[warehouse.Corpus] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a corpus inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateCorpusRequest, dict]]): + The request object. Request message of CreateCorpus API. + parent (:class:`str`): + Required. Form: + ``projects/{project_number}/locations/{location_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + corpus (:class:`google.cloud.visionai_v1alpha1.types.Corpus`): + Required. The corpus to be created. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Corpus` Corpus is a set of video contents for management. Within a corpus, videos + share the same data schema. Search is also restricted + within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, corpus]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateCorpusRequest): + request = warehouse.CreateCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if corpus is not None: + request.corpus = corpus + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + warehouse.Corpus, + metadata_type=warehouse.CreateCorpusMetadata, + ) + + # Done; return the response. + return response + + async def get_corpus(self, + request: Optional[Union[warehouse.GetCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Gets corpus details inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetCorpusRequest, dict]]): + The request object. Request message for GetCorpus. + name (:class:`str`): + Required. The resource name of the + corpus to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Corpus: + Corpus is a set of video contents for + management. Within a corpus, videos + share the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetCorpusRequest): + request = warehouse.GetCorpusRequest(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._client._transport._wrapped_methods[self._client._transport.get_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_corpus(self, + request: Optional[Union[warehouse.UpdateCorpusRequest, dict]] = None, + *, + corpus: Optional[warehouse.Corpus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Updates a corpus in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = await client.update_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateCorpusRequest, dict]]): + The request object. Request message for UpdateCorpus. + corpus (:class:`google.cloud.visionai_v1alpha1.types.Corpus`): + Required. The corpus which replaces + the resource on the server. + + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Corpus: + Corpus is a set of video contents for + management. Within a corpus, videos + share the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateCorpusRequest): + request = warehouse.UpdateCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + 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._client._transport._wrapped_methods[self._client._transport.update_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus.name", request.corpus.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_corpora(self, + request: Optional[Union[warehouse.ListCorporaRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCorporaAsyncPager: + r"""Lists all corpora in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_corpora(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListCorporaRequest, dict]]): + The request object. Request message for ListCorpora. + parent (:class:`str`): + Required. The resource name of the + project from which to list corpora. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListCorporaAsyncPager: + Response message for ListCorpora. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListCorporaRequest): + request = warehouse.ListCorporaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_corpora] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListCorporaAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_corpus(self, + request: Optional[Union[warehouse.DeleteCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a corpus only if its empty. + Returns empty response. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + await client.delete_corpus(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteCorpusRequest, dict]]): + The request object. Request message for DeleteCorpus. + name (:class:`str`): + Required. The resource name of the + corpus to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteCorpusRequest): + request = warehouse.DeleteCorpusRequest(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._client._transport._wrapped_methods[self._client._transport.delete_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_data_schema(self, + request: Optional[Union[warehouse.CreateDataSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_schema: Optional[warehouse.DataSchema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Creates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = await client.create_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateDataSchemaRequest, dict]]): + The request object. Request message for CreateDataSchema. + parent (:class:`str`): + Required. The parent resource where this data schema + will be created. Format: + projects/\ */locations/*/corpora/\* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_schema (:class:`google.cloud.visionai_v1alpha1.types.DataSchema`): + Required. The data schema to create. + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_schema]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateDataSchemaRequest): + request = warehouse.CreateDataSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_schema is not None: + request.data_schema = data_schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_data_schema(self, + request: Optional[Union[warehouse.UpdateDataSchemaRequest, dict]] = None, + *, + data_schema: Optional[warehouse.DataSchema] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Updates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = await client.update_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateDataSchemaRequest, dict]]): + The request object. Request message for UpdateDataSchema. + data_schema (:class:`google.cloud.visionai_v1alpha1.types.DataSchema`): + Required. The data schema's ``name`` field is used to + identify the data schema to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema} + + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_schema, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateDataSchemaRequest): + request = warehouse.UpdateDataSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_schema is not None: + request.data_schema = data_schema + 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._client._transport._wrapped_methods[self._client._transport.update_data_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_schema.name", request.data_schema.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_schema(self, + request: Optional[Union[warehouse.GetDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Gets data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetDataSchemaRequest, dict]]): + The request object. Request message for GetDataSchema. + name (:class:`str`): + Required. The name of the data schema to retrieve. + Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetDataSchemaRequest): + request = warehouse.GetDataSchemaRequest(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._client._transport._wrapped_methods[self._client._transport.get_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_data_schema(self, + request: Optional[Union[warehouse.DeleteDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_schema(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteDataSchemaRequest, dict]]): + The request object. Request message for DeleteDataSchema. + name (:class:`str`): + Required. The name of the data schema to delete. Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteDataSchemaRequest): + request = warehouse.DeleteDataSchemaRequest(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._client._transport._wrapped_methods[self._client._transport.delete_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_data_schemas(self, + request: Optional[Union[warehouse.ListDataSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataSchemasAsyncPager: + r"""Lists a list of data schemas inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_data_schemas(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListDataSchemasRequest, dict]]): + The request object. Request message for ListDataSchemas. + parent (:class:`str`): + Required. The parent, which owns this collection of data + schemas. Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListDataSchemasAsyncPager: + Response message for ListDataSchemas. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListDataSchemasRequest): + request = warehouse.ListDataSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_data_schemas] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListDataSchemasAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_annotation(self, + request: Optional[Union[warehouse.CreateAnnotationRequest, dict]] = None, + *, + parent: Optional[str] = None, + annotation: Optional[warehouse.Annotation] = None, + annotation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Creates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateAnnotationRequest, dict]]): + The request object. Request message for CreateAnnotation. + parent (:class:`str`): + Required. The parent resource where this annotation will + be created. Format: + projects/\ */locations/*/corpora/*/assets/* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation (:class:`google.cloud.visionai_v1alpha1.types.Annotation`): + Required. The annotation to create. + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation_id (:class:`str`): + Optional. The ID to use for the annotation, which will + become the final component of the annotation's resource + name if user choose to specify. Otherwise, annotation id + will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``annotation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, annotation, annotation_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAnnotationRequest): + request = warehouse.CreateAnnotationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if annotation is not None: + request.annotation = annotation + if annotation_id is not None: + request.annotation_id = annotation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_annotation(self, + request: Optional[Union[warehouse.GetAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Reads annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetAnnotationRequest, dict]]): + The request object. Request message for GetAnnotation + API. + name (:class:`str`): + Required. The name of the annotation to retrieve. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAnnotationRequest): + request = warehouse.GetAnnotationRequest(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._client._transport._wrapped_methods[self._client._transport.get_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_annotations(self, + request: Optional[Union[warehouse.ListAnnotationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotationsAsyncPager: + r"""Lists a list of annotations inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_annotations(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListAnnotationsRequest, dict]]): + The request object. Request message for GetAnnotation + API. + parent (:class:`str`): + The parent, which owns this collection of annotations. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAnnotationsAsyncPager: + Request message for ListAnnotations + API. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAnnotationsRequest): + request = warehouse.ListAnnotationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_annotations] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAnnotationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_annotation(self, + request: Optional[Union[warehouse.UpdateAnnotationRequest, dict]] = None, + *, + annotation: Optional[warehouse.Annotation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Updates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnnotationRequest( + ) + + # Make the request + response = await client.update_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateAnnotationRequest, dict]]): + The request object. Request message for UpdateAnnotation + API. + annotation (:class:`google.cloud.visionai_v1alpha1.types.Annotation`): + Required. The annotation to update. The annotation's + ``name`` field is used to identify the annotation to be + updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([annotation, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAnnotationRequest): + request = warehouse.UpdateAnnotationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if annotation is not None: + request.annotation = annotation + 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._client._transport._wrapped_methods[self._client._transport.update_annotation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("annotation.name", request.annotation.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_annotation(self, + request: Optional[Union[warehouse.DeleteAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + await client.delete_annotation(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteAnnotationRequest, dict]]): + The request object. Request message for DeleteAnnotation + API. + name (:class:`str`): + Required. The name of the annotation to delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAnnotationRequest): + request = warehouse.DeleteAnnotationRequest(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._client._transport._wrapped_methods[self._client._transport.delete_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def ingest_asset(self, + requests: Optional[AsyncIterator[warehouse.IngestAssetRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[warehouse.IngestAssetResponse]]: + r"""Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_ingest_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + config = visionai_v1alpha1.Config() + config.asset = "asset_value" + + request = visionai_v1alpha1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.ingest_asset(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.visionai_v1alpha1.types.IngestAssetRequest`]): + The request object AsyncIterator. Request message for IngestAsset API. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.visionai_v1alpha1.types.IngestAssetResponse]: + Response message for IngestAsset API. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.ingest_asset] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def clip_asset(self, + request: Optional[Union[warehouse.ClipAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.ClipAssetResponse: + r"""Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_clip_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.clip_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ClipAssetRequest, dict]]): + The request object. Request message for ClipAsset API. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.ClipAssetResponse: + Response message for ClipAsset API. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ClipAssetRequest): + request = warehouse.ClipAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.clip_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_hls_uri(self, + request: Optional[Union[warehouse.GenerateHlsUriRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.GenerateHlsUriResponse: + r"""Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_generate_hls_uri(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_hls_uri(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GenerateHlsUriRequest, dict]]): + The request object. Request message for GenerateHlsUri + API. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.GenerateHlsUriResponse: + Response message for GenerateHlsUri + API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GenerateHlsUriRequest): + request = warehouse.GenerateHlsUriRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_hls_uri] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_search_config(self, + request: Optional[Union[warehouse.CreateSearchConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_config: Optional[warehouse.SearchConfig] = None, + search_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_create_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = await client.create_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.CreateSearchConfigRequest, dict]]): + The request object. Request message for + CreateSearchConfig. + parent (:class:`str`): + Required. The parent resource where this search + configuration will be created. Format: + projects/\ */locations/*/corpora/\* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config (:class:`google.cloud.visionai_v1alpha1.types.SearchConfig`): + Required. The search config to + create. + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config_id (:class:`str`): + Required. ID to use for the new search config. Will + become the final component of the SearchConfig's + resource name. This value should be up to 63 characters, + and valid characters are /[a-z][0-9]-_/. The first + character must be a letter, the last could be a letter + or a number. + + This corresponds to the ``search_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_config, search_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateSearchConfigRequest): + request = warehouse.CreateSearchConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_config is not None: + request.search_config = search_config + if search_config_id is not None: + request.search_config_id = search_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_search_config(self, + request: Optional[Union[warehouse.UpdateSearchConfigRequest, dict]] = None, + *, + search_config: Optional[warehouse.SearchConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_update_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateSearchConfigRequest( + ) + + # Make the request + response = await client.update_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.UpdateSearchConfigRequest, dict]]): + The request object. Request message for + UpdateSearchConfig. + search_config (:class:`google.cloud.visionai_v1alpha1.types.SearchConfig`): + Required. The search configuration to update. + + The search configuration's ``name`` field is used to + identify the resource to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If + left unset, all field paths will be + updated/overwritten. + + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_config, 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.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateSearchConfigRequest): + request = warehouse.UpdateSearchConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_config is not None: + request.search_config = search_config + 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._client._transport._wrapped_methods[self._client._transport.update_search_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_config.name", request.search_config.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_search_config(self, + request: Optional[Union[warehouse.GetSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Gets a search configuration inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_get_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.GetSearchConfigRequest, dict]]): + The request object. Request message for GetSearchConfig. + name (:class:`str`): + Required. The name of the search configuration to + retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetSearchConfigRequest): + request = warehouse.GetSearchConfigRequest(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._client._transport._wrapped_methods[self._client._transport.get_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_search_config(self, + request: Optional[Union[warehouse.DeleteSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_delete_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_search_config(request=request) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.DeleteSearchConfigRequest, dict]]): + The request object. Request message for + DeleteSearchConfig. + name (:class:`str`): + Required. The name of the search configuration to + delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteSearchConfigRequest): + request = warehouse.DeleteSearchConfigRequest(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._client._transport._wrapped_methods[self._client._transport.delete_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_search_configs(self, + request: Optional[Union[warehouse.ListSearchConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSearchConfigsAsyncPager: + r"""Lists all search configurations inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_list_search_configs(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.ListSearchConfigsRequest, dict]]): + The request object. Request message for + ListSearchConfigs. + parent (:class:`str`): + Required. The parent, which owns this collection of + search configurations. Format: + projects/{project_number}/locations/{location}/corpora/{corpus} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListSearchConfigsAsyncPager: + Response message for + ListSearchConfigs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListSearchConfigsRequest): + request = warehouse.ListSearchConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_search_configs] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListSearchConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_assets(self, + request: Optional[Union[warehouse.SearchAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAssetsAsyncPager: + r"""Search media asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + async def sample_search_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.visionai_v1alpha1.types.SearchAssetsRequest, dict]]): + The request object. Request message for SearchAssets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.SearchAssetsAsyncPager: + Response message for SearchAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.SearchAssetsRequest): + request = warehouse.SearchAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus", request.corpus), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.SearchAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "WarehouseAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "WarehouseAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/client.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/client.py new file mode 100644 index 000000000000..e92d3a51e2a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/client.py @@ -0,0 +1,4426 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.services.warehouse import pagers +from google.cloud.visionai_v1alpha1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WarehouseTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WarehouseGrpcTransport +from .transports.grpc_asyncio import WarehouseGrpcAsyncIOTransport +from .transports.rest import WarehouseRestTransport + + +class WarehouseClientMeta(type): + """Metaclass for the Warehouse 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[WarehouseTransport]] + _transport_registry["grpc"] = WarehouseGrpcTransport + _transport_registry["grpc_asyncio"] = WarehouseGrpcAsyncIOTransport + _transport_registry["rest"] = WarehouseRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WarehouseTransport]: + """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 WarehouseClient(metaclass=WarehouseClientMeta): + """Service that manages media content + metadata for streaming.""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "visionai.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "visionai.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + WarehouseClient: 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: + WarehouseClient: 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) -> WarehouseTransport: + """Returns the transport used by the client instance. + + Returns: + WarehouseTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def annotation_path(project_number: str,location: str,corpus: str,asset: str,annotation: str,) -> str: + """Returns a fully-qualified annotation string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, annotation=annotation, ) + + @staticmethod + def parse_annotation_path(path: str) -> Dict[str,str]: + """Parses a annotation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/assets/(?P.+?)/annotations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def asset_path(project_number: str,location: str,corpus: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def corpus_path(project_number: str,location: str,corpus: str,) -> str: + """Returns a fully-qualified corpus string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}".format(project_number=project_number, location=location, corpus=corpus, ) + + @staticmethod + def parse_corpus_path(path: str) -> Dict[str,str]: + """Parses a corpus path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_schema_path(project_number: str,location: str,corpus: str,data_schema: str,) -> str: + """Returns a fully-qualified data_schema string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}".format(project_number=project_number, location=location, corpus=corpus, data_schema=data_schema, ) + + @staticmethod + def parse_data_schema_path(path: str) -> Dict[str,str]: + """Parses a data_schema path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/dataSchemas/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def search_config_path(project_number: str,location: str,corpus: str,search_config: str,) -> str: + """Returns a fully-qualified search_config string.""" + return "projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}".format(project_number=project_number, location=location, corpus=corpus, search_config=search_config, ) + + @staticmethod + def parse_search_config_path(path: str) -> Dict[str,str]: + """Parses a search_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/corpora/(?P.+?)/searchConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = WarehouseClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = WarehouseClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = WarehouseClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = WarehouseClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + WarehouseClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, WarehouseTransport, Callable[..., WarehouseTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the warehouse 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 (Optional[Union[str,WarehouseTransport,Callable[..., WarehouseTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the WarehouseTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = WarehouseClient._read_environment_variables() + self._client_cert_source = WarehouseClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = WarehouseClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, WarehouseTransport) + if transport_provided: + # transport is a WarehouseTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(WarehouseTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + WarehouseClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[WarehouseTransport], Callable[..., WarehouseTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WarehouseTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def create_asset(self, + request: Optional[Union[warehouse.CreateAssetRequest, dict]] = None, + *, + parent: Optional[str] = None, + asset: Optional[warehouse.Asset] = None, + asset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Creates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateAssetRequest, dict]): + The request object. Request message for + CreateAssetRequest. + parent (str): + Required. The parent resource where this asset will be + created. Format: projects/\ */locations/*/corpora/\* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset (google.cloud.visionai_v1alpha1.types.Asset): + Required. The asset to create. + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_id (str): + Optional. The ID to use for the asset, which will become + the final component of the asset's resource name if user + choose to specify. Otherwise, asset id will be generated + by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``asset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, asset, asset_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAssetRequest): + request = warehouse.CreateAssetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if asset is not None: + request.asset = asset + if asset_id is not None: + request.asset_id = asset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_asset(self, + request: Optional[Union[warehouse.UpdateAssetRequest, dict]] = None, + *, + asset: Optional[warehouse.Asset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Updates an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAssetRequest( + ) + + # Make the request + response = client.update_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateAssetRequest, dict]): + The request object. Response message for UpdateAsset. + asset (google.cloud.visionai_v1alpha1.types.Asset): + Required. The asset to update. + + The asset's ``name`` field is used to identify the asset + to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``asset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([asset, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAssetRequest): + request = warehouse.UpdateAssetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if asset is not None: + request.asset = asset + 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_asset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("asset.name", request.asset.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_asset(self, + request: Optional[Union[warehouse.GetAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Asset: + r"""Reads an asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = client.get_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetAssetRequest, dict]): + The request object. Request message for GetAsset. + name (str): + Required. The name of the asset to retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAssetRequest): + request = warehouse.GetAssetRequest(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_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[warehouse.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an list of assets inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListAssetsRequest, dict]): + The request object. Request message for ListAssets. + parent (str): + Required. The parent, which owns this collection of + assets. Format: + projects/{project_number}/locations/{location}/corpora/{corpus} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAssetsPager: + Response message for ListAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAssetsRequest): + request = warehouse.ListAssetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_asset(self, + request: Optional[Union[warehouse.DeleteAssetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes asset inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteAssetRequest, dict]): + The request object. Request message for DeleteAsset. + name (str): + Required. The name of the asset to delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAssetRequest): + request = warehouse.DeleteAssetRequest(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_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=warehouse.DeleteAssetMetadata, + ) + + # Done; return the response. + return response + + def create_corpus(self, + request: Optional[Union[warehouse.CreateCorpusRequest, dict]] = None, + *, + parent: Optional[str] = None, + corpus: Optional[warehouse.Corpus] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a corpus inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateCorpusRequest, dict]): + The request object. Request message of CreateCorpus API. + parent (str): + Required. Form: + ``projects/{project_number}/locations/{location_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + corpus (google.cloud.visionai_v1alpha1.types.Corpus): + Required. The corpus to be created. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.visionai_v1alpha1.types.Corpus` Corpus is a set of video contents for management. Within a corpus, videos + share the same data schema. Search is also restricted + within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, corpus]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateCorpusRequest): + request = warehouse.CreateCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if corpus is not None: + request.corpus = corpus + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + warehouse.Corpus, + metadata_type=warehouse.CreateCorpusMetadata, + ) + + # Done; return the response. + return response + + def get_corpus(self, + request: Optional[Union[warehouse.GetCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Gets corpus details inside a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = client.get_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetCorpusRequest, dict]): + The request object. Request message for GetCorpus. + name (str): + Required. The resource name of the + corpus to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Corpus: + Corpus is a set of video contents for + management. Within a corpus, videos + share the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetCorpusRequest): + request = warehouse.GetCorpusRequest(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_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_corpus(self, + request: Optional[Union[warehouse.UpdateCorpusRequest, dict]] = None, + *, + corpus: Optional[warehouse.Corpus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Corpus: + r"""Updates a corpus in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = client.update_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateCorpusRequest, dict]): + The request object. Request message for UpdateCorpus. + corpus (google.cloud.visionai_v1alpha1.types.Corpus): + Required. The corpus which replaces + the resource on the server. + + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Corpus: + Corpus is a set of video contents for + management. Within a corpus, videos + share the same data schema. Search is + also restricted within a single corpus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateCorpusRequest): + request = warehouse.UpdateCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + 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_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus.name", request.corpus.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_corpora(self, + request: Optional[Union[warehouse.ListCorporaRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCorporaPager: + r"""Lists all corpora in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_corpora(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListCorporaRequest, dict]): + The request object. Request message for ListCorpora. + parent (str): + Required. The resource name of the + project from which to list corpora. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListCorporaPager: + Response message for ListCorpora. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListCorporaRequest): + request = warehouse.ListCorporaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_corpora] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListCorporaPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_corpus(self, + request: Optional[Union[warehouse.DeleteCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a corpus only if its empty. + Returns empty response. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + client.delete_corpus(request=request) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteCorpusRequest, dict]): + The request object. Request message for DeleteCorpus. + name (str): + Required. The resource name of the + corpus to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteCorpusRequest): + request = warehouse.DeleteCorpusRequest(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_corpus] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_data_schema(self, + request: Optional[Union[warehouse.CreateDataSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_schema: Optional[warehouse.DataSchema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Creates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = client.create_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateDataSchemaRequest, dict]): + The request object. Request message for CreateDataSchema. + parent (str): + Required. The parent resource where this data schema + will be created. Format: + projects/\ */locations/*/corpora/\* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_schema (google.cloud.visionai_v1alpha1.types.DataSchema): + Required. The data schema to create. + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_schema]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateDataSchemaRequest): + request = warehouse.CreateDataSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_schema is not None: + request.data_schema = data_schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_data_schema(self, + request: Optional[Union[warehouse.UpdateDataSchemaRequest, dict]] = None, + *, + data_schema: Optional[warehouse.DataSchema] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Updates data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = client.update_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateDataSchemaRequest, dict]): + The request object. Request message for UpdateDataSchema. + data_schema (google.cloud.visionai_v1alpha1.types.DataSchema): + Required. The data schema's ``name`` field is used to + identify the data schema to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema} + + This corresponds to the ``data_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_schema, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateDataSchemaRequest): + request = warehouse.UpdateDataSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_schema is not None: + request.data_schema = data_schema + 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_data_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_schema.name", request.data_schema.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_schema(self, + request: Optional[Union[warehouse.GetDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.DataSchema: + r"""Gets data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetDataSchemaRequest, dict]): + The request object. Request message for GetDataSchema. + name (str): + Required. The name of the data schema to retrieve. + Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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: + google.cloud.visionai_v1alpha1.types.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetDataSchemaRequest): + request = warehouse.GetDataSchemaRequest(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_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_data_schema(self, + request: Optional[Union[warehouse.DeleteDataSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes data schema inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + client.delete_data_schema(request=request) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteDataSchemaRequest, dict]): + The request object. Request message for DeleteDataSchema. + name (str): + Required. The name of the data schema to delete. Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteDataSchemaRequest): + request = warehouse.DeleteDataSchemaRequest(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_data_schema] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_data_schemas(self, + request: Optional[Union[warehouse.ListDataSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataSchemasPager: + r"""Lists a list of data schemas inside corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_data_schemas(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListDataSchemasRequest, dict]): + The request object. Request message for ListDataSchemas. + parent (str): + Required. The parent, which owns this collection of data + schemas. Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListDataSchemasPager: + Response message for ListDataSchemas. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListDataSchemasRequest): + request = warehouse.ListDataSchemasRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_data_schemas] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListDataSchemasPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_annotation(self, + request: Optional[Union[warehouse.CreateAnnotationRequest, dict]] = None, + *, + parent: Optional[str] = None, + annotation: Optional[warehouse.Annotation] = None, + annotation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Creates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateAnnotationRequest, dict]): + The request object. Request message for CreateAnnotation. + parent (str): + Required. The parent resource where this annotation will + be created. Format: + projects/\ */locations/*/corpora/*/assets/* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation (google.cloud.visionai_v1alpha1.types.Annotation): + Required. The annotation to create. + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation_id (str): + Optional. The ID to use for the annotation, which will + become the final component of the annotation's resource + name if user choose to specify. Otherwise, annotation id + will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + + This corresponds to the ``annotation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, annotation, annotation_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateAnnotationRequest): + request = warehouse.CreateAnnotationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if annotation is not None: + request.annotation = annotation + if annotation_id is not None: + request.annotation_id = annotation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_annotation(self, + request: Optional[Union[warehouse.GetAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Reads annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = client.get_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetAnnotationRequest, dict]): + The request object. Request message for GetAnnotation + API. + name (str): + Required. The name of the annotation to retrieve. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetAnnotationRequest): + request = warehouse.GetAnnotationRequest(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_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_annotations(self, + request: Optional[Union[warehouse.ListAnnotationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnnotationsPager: + r"""Lists a list of annotations inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_annotations(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListAnnotationsRequest, dict]): + The request object. Request message for GetAnnotation + API. + parent (str): + The parent, which owns this collection of annotations. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAnnotationsPager: + Request message for ListAnnotations + API. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListAnnotationsRequest): + request = warehouse.ListAnnotationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_annotations] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAnnotationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_annotation(self, + request: Optional[Union[warehouse.UpdateAnnotationRequest, dict]] = None, + *, + annotation: Optional[warehouse.Annotation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.Annotation: + r"""Updates annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnnotationRequest( + ) + + # Make the request + response = client.update_annotation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateAnnotationRequest, dict]): + The request object. Request message for UpdateAnnotation + API. + annotation (google.cloud.visionai_v1alpha1.types.Annotation): + Required. The annotation to update. The annotation's + ``name`` field is used to identify the annotation to be + updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([annotation, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateAnnotationRequest): + request = warehouse.UpdateAnnotationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if annotation is not None: + request.annotation = annotation + 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_annotation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("annotation.name", request.annotation.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_annotation(self, + request: Optional[Union[warehouse.DeleteAnnotationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes annotation inside asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + client.delete_annotation(request=request) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteAnnotationRequest, dict]): + The request object. Request message for DeleteAnnotation + API. + name (str): + Required. The name of the annotation to delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + + 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteAnnotationRequest): + request = warehouse.DeleteAnnotationRequest(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_annotation] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def ingest_asset(self, + requests: Optional[Iterator[warehouse.IngestAssetRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[warehouse.IngestAssetResponse]: + r"""Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_ingest_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + config = visionai_v1alpha1.Config() + config.asset = "asset_value" + + request = visionai_v1alpha1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.ingest_asset(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.visionai_v1alpha1.types.IngestAssetRequest]): + The request object iterator. Request message for IngestAsset API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.visionai_v1alpha1.types.IngestAssetResponse]: + Response message for IngestAsset API. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.ingest_asset] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def clip_asset(self, + request: Optional[Union[warehouse.ClipAssetRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.ClipAssetResponse: + r"""Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_clip_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = client.clip_asset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ClipAssetRequest, dict]): + The request object. Request message for ClipAsset API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.ClipAssetResponse: + Response message for ClipAsset API. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ClipAssetRequest): + request = warehouse.ClipAssetRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.clip_asset] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_hls_uri(self, + request: Optional[Union[warehouse.GenerateHlsUriRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.GenerateHlsUriResponse: + r"""Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_generate_hls_uri(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = client.generate_hls_uri(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GenerateHlsUriRequest, dict]): + The request object. Request message for GenerateHlsUri + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.GenerateHlsUriResponse: + Response message for GenerateHlsUri + API. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GenerateHlsUriRequest): + request = warehouse.GenerateHlsUriRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_hls_uri] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_search_config(self, + request: Optional[Union[warehouse.CreateSearchConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_config: Optional[warehouse.SearchConfig] = None, + search_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_create_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = client.create_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.CreateSearchConfigRequest, dict]): + The request object. Request message for + CreateSearchConfig. + parent (str): + Required. The parent resource where this search + configuration will be created. Format: + projects/\ */locations/*/corpora/\* + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config (google.cloud.visionai_v1alpha1.types.SearchConfig): + Required. The search config to + create. + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_config_id (str): + Required. ID to use for the new search config. Will + become the final component of the SearchConfig's + resource name. This value should be up to 63 characters, + and valid characters are /[a-z][0-9]-_/. The first + character must be a letter, the last could be a letter + or a number. + + This corresponds to the ``search_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_config, search_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.CreateSearchConfigRequest): + request = warehouse.CreateSearchConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_config is not None: + request.search_config = search_config + if search_config_id is not None: + request.search_config_id = search_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_search_config(self, + request: Optional[Union[warehouse.UpdateSearchConfigRequest, dict]] = None, + *, + search_config: Optional[warehouse.SearchConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_update_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateSearchConfigRequest( + ) + + # Make the request + response = client.update_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.UpdateSearchConfigRequest, dict]): + The request object. Request message for + UpdateSearchConfig. + search_config (google.cloud.visionai_v1alpha1.types.SearchConfig): + Required. The search configuration to update. + + The search configuration's ``name`` field is used to + identify the resource to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + + This corresponds to the ``search_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If + left unset, all field paths will be + updated/overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_config, 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.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.UpdateSearchConfigRequest): + request = warehouse.UpdateSearchConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_config is not None: + request.search_config = search_config + 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_search_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_config.name", request.search_config.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_search_config(self, + request: Optional[Union[warehouse.GetSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> warehouse.SearchConfig: + r"""Gets a search configuration inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_get_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_search_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.GetSearchConfigRequest, dict]): + The request object. Request message for GetSearchConfig. + name (str): + Required. The name of the search configuration to + retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.types.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.GetSearchConfigRequest): + request = warehouse.GetSearchConfigRequest(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_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_search_config(self, + request: Optional[Union[warehouse.DeleteSearchConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_delete_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_search_config(request=request) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.DeleteSearchConfigRequest, dict]): + The request object. Request message for + DeleteSearchConfig. + name (str): + Required. The name of the search configuration to + delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + + 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. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.DeleteSearchConfigRequest): + request = warehouse.DeleteSearchConfigRequest(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_search_config] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_search_configs(self, + request: Optional[Union[warehouse.ListSearchConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSearchConfigsPager: + r"""Lists all search configurations inside a corpus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_list_search_configs(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.ListSearchConfigsRequest, dict]): + The request object. Request message for + ListSearchConfigs. + parent (str): + Required. The parent, which owns this collection of + search configurations. Format: + projects/{project_number}/locations/{location}/corpora/{corpus} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListSearchConfigsPager: + Response message for + ListSearchConfigs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.ListSearchConfigsRequest): + request = warehouse.ListSearchConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_search_configs] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListSearchConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_assets(self, + request: Optional[Union[warehouse.SearchAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAssetsPager: + r"""Search media asset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import visionai_v1alpha1 + + def sample_search_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.visionai_v1alpha1.types.SearchAssetsRequest, dict]): + The request object. Request message for SearchAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.visionai_v1alpha1.services.warehouse.pagers.SearchAssetsPager: + Response message for SearchAssets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, warehouse.SearchAssetsRequest): + request = warehouse.SearchAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("corpus", request.corpus), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.SearchAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "WarehouseClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "WarehouseClient", +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/pagers.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/pagers.py new file mode 100644 index 000000000000..7c037a3c2ee5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/pagers.py @@ -0,0 +1,744 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.visionai_v1alpha1.types import warehouse + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListAssetsResponse` + 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[..., warehouse.ListAssetsResponse], + request: warehouse.ListAssetsRequest, + response: warehouse.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListAssetsResponse): + 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 = warehouse.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Asset]: + for page in self.pages: + yield from page.assets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListAssetsResponse` + 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[warehouse.ListAssetsResponse]], + request: warehouse.ListAssetsRequest, + response: warehouse.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListAssetsResponse): + 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 = warehouse.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Asset]: + async def async_generator(): + async for page in self.pages: + for response in page.assets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCorporaPager: + """A pager for iterating through ``list_corpora`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListCorporaResponse` object, and + provides an ``__iter__`` method to iterate through its + ``corpora`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCorpora`` requests and continue to iterate + through the ``corpora`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListCorporaResponse` + 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[..., warehouse.ListCorporaResponse], + request: warehouse.ListCorporaRequest, + response: warehouse.ListCorporaResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListCorporaRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListCorporaResponse): + 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 = warehouse.ListCorporaRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListCorporaResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Corpus]: + for page in self.pages: + yield from page.corpora + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCorporaAsyncPager: + """A pager for iterating through ``list_corpora`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListCorporaResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``corpora`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCorpora`` requests and continue to iterate + through the ``corpora`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListCorporaResponse` + 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[warehouse.ListCorporaResponse]], + request: warehouse.ListCorporaRequest, + response: warehouse.ListCorporaResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListCorporaRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListCorporaResponse): + 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 = warehouse.ListCorporaRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListCorporaResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Corpus]: + async def async_generator(): + async for page in self.pages: + for response in page.corpora: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataSchemasPager: + """A pager for iterating through ``list_data_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListDataSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataSchemas`` requests and continue to iterate + through the ``data_schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListDataSchemasResponse` + 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[..., warehouse.ListDataSchemasResponse], + request: warehouse.ListDataSchemasRequest, + response: warehouse.ListDataSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListDataSchemasRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListDataSchemasResponse): + 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 = warehouse.ListDataSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListDataSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.DataSchema]: + for page in self.pages: + yield from page.data_schemas + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataSchemasAsyncPager: + """A pager for iterating through ``list_data_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListDataSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataSchemas`` requests and continue to iterate + through the ``data_schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListDataSchemasResponse` + 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[warehouse.ListDataSchemasResponse]], + request: warehouse.ListDataSchemasRequest, + response: warehouse.ListDataSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListDataSchemasRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListDataSchemasResponse): + 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 = warehouse.ListDataSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListDataSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.DataSchema]: + async def async_generator(): + async for page in self.pages: + for response in page.data_schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotationsPager: + """A pager for iterating through ``list_annotations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListAnnotationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``annotations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnnotations`` requests and continue to iterate + through the ``annotations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListAnnotationsResponse` + 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[..., warehouse.ListAnnotationsResponse], + request: warehouse.ListAnnotationsRequest, + response: warehouse.ListAnnotationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListAnnotationsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListAnnotationsResponse): + 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 = warehouse.ListAnnotationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListAnnotationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.Annotation]: + for page in self.pages: + yield from page.annotations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnnotationsAsyncPager: + """A pager for iterating through ``list_annotations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListAnnotationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``annotations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnnotations`` requests and continue to iterate + through the ``annotations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListAnnotationsResponse` + 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[warehouse.ListAnnotationsResponse]], + request: warehouse.ListAnnotationsRequest, + response: warehouse.ListAnnotationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListAnnotationsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListAnnotationsResponse): + 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 = warehouse.ListAnnotationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListAnnotationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.Annotation]: + async def async_generator(): + async for page in self.pages: + for response in page.annotations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchConfigsPager: + """A pager for iterating through ``list_search_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListSearchConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``search_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSearchConfigs`` requests and continue to iterate + through the ``search_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListSearchConfigsResponse` + 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[..., warehouse.ListSearchConfigsResponse], + request: warehouse.ListSearchConfigsRequest, + response: warehouse.ListSearchConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListSearchConfigsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListSearchConfigsResponse): + 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 = warehouse.ListSearchConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.ListSearchConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.SearchConfig]: + for page in self.pages: + yield from page.search_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchConfigsAsyncPager: + """A pager for iterating through ``list_search_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.ListSearchConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``search_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSearchConfigs`` requests and continue to iterate + through the ``search_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.ListSearchConfigsResponse` + 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[warehouse.ListSearchConfigsResponse]], + request: warehouse.ListSearchConfigsRequest, + response: warehouse.ListSearchConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.ListSearchConfigsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.ListSearchConfigsResponse): + 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 = warehouse.ListSearchConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.ListSearchConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.SearchConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.search_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAssetsPager: + """A pager for iterating through ``search_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.SearchAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``search_result_items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAssets`` requests and continue to iterate + through the ``search_result_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.SearchAssetsResponse` + 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[..., warehouse.SearchAssetsResponse], + request: warehouse.SearchAssetsRequest, + response: warehouse.SearchAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.SearchAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.SearchAssetsResponse): + 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 = warehouse.SearchAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[warehouse.SearchAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[warehouse.SearchResultItem]: + for page in self.pages: + yield from page.search_result_items + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAssetsAsyncPager: + """A pager for iterating through ``search_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.visionai_v1alpha1.types.SearchAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``search_result_items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAssets`` requests and continue to iterate + through the ``search_result_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.visionai_v1alpha1.types.SearchAssetsResponse` + 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[warehouse.SearchAssetsResponse]], + request: warehouse.SearchAssetsRequest, + response: warehouse.SearchAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.visionai_v1alpha1.types.SearchAssetsRequest): + The initial request object. + response (google.cloud.visionai_v1alpha1.types.SearchAssetsResponse): + 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 = warehouse.SearchAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[warehouse.SearchAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[warehouse.SearchResultItem]: + async def async_generator(): + async for page in self.pages: + for response in page.search_result_items: + 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/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/__init__.py new file mode 100644 index 000000000000..c7ec5d9728c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 WarehouseTransport +from .grpc import WarehouseGrpcTransport +from .grpc_asyncio import WarehouseGrpcAsyncIOTransport +from .rest import WarehouseRestTransport +from .rest import WarehouseRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WarehouseTransport]] +_transport_registry['grpc'] = WarehouseGrpcTransport +_transport_registry['grpc_asyncio'] = WarehouseGrpcAsyncIOTransport +_transport_registry['rest'] = WarehouseRestTransport + +__all__ = ( + 'WarehouseTransport', + 'WarehouseGrpcTransport', + 'WarehouseGrpcAsyncIOTransport', + 'WarehouseRestTransport', + 'WarehouseRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/base.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/base.py new file mode 100644 index 000000000000..4be2aa054f5a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/base.py @@ -0,0 +1,687 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.cloud.visionai_v1alpha1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WarehouseTransport(abc.ABC): + """Abstract transport class for Warehouse.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'visionai.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_asset: gapic_v1.method.wrap_method( + self.create_asset, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_asset: gapic_v1.method.wrap_method( + self.update_asset, + default_timeout=None, + client_info=client_info, + ), + self.get_asset: gapic_v1.method.wrap_method( + self.get_asset, + default_timeout=None, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_timeout=None, + client_info=client_info, + ), + self.delete_asset: gapic_v1.method.wrap_method( + self.delete_asset, + default_timeout=None, + client_info=client_info, + ), + self.create_corpus: gapic_v1.method.wrap_method( + self.create_corpus, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_corpus: gapic_v1.method.wrap_method( + self.get_corpus, + default_timeout=None, + client_info=client_info, + ), + self.update_corpus: gapic_v1.method.wrap_method( + self.update_corpus, + default_timeout=None, + client_info=client_info, + ), + self.list_corpora: gapic_v1.method.wrap_method( + self.list_corpora, + default_timeout=None, + client_info=client_info, + ), + self.delete_corpus: gapic_v1.method.wrap_method( + self.delete_corpus, + default_timeout=None, + client_info=client_info, + ), + self.create_data_schema: gapic_v1.method.wrap_method( + self.create_data_schema, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_data_schema: gapic_v1.method.wrap_method( + self.update_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.get_data_schema: gapic_v1.method.wrap_method( + self.get_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_schema: gapic_v1.method.wrap_method( + self.delete_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_data_schemas: gapic_v1.method.wrap_method( + self.list_data_schemas, + default_timeout=None, + client_info=client_info, + ), + self.create_annotation: gapic_v1.method.wrap_method( + self.create_annotation, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_annotation: gapic_v1.method.wrap_method( + self.get_annotation, + default_timeout=None, + client_info=client_info, + ), + self.list_annotations: gapic_v1.method.wrap_method( + self.list_annotations, + default_timeout=None, + client_info=client_info, + ), + self.update_annotation: gapic_v1.method.wrap_method( + self.update_annotation, + default_timeout=None, + client_info=client_info, + ), + self.delete_annotation: gapic_v1.method.wrap_method( + self.delete_annotation, + default_timeout=None, + client_info=client_info, + ), + self.ingest_asset: gapic_v1.method.wrap_method( + self.ingest_asset, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.clip_asset: gapic_v1.method.wrap_method( + self.clip_asset, + default_timeout=None, + client_info=client_info, + ), + self.generate_hls_uri: gapic_v1.method.wrap_method( + self.generate_hls_uri, + default_timeout=None, + client_info=client_info, + ), + self.create_search_config: gapic_v1.method.wrap_method( + self.create_search_config, + default_timeout=None, + client_info=client_info, + ), + self.update_search_config: gapic_v1.method.wrap_method( + self.update_search_config, + default_timeout=None, + client_info=client_info, + ), + self.get_search_config: gapic_v1.method.wrap_method( + self.get_search_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_config: gapic_v1.method.wrap_method( + self.delete_search_config, + default_timeout=None, + client_info=client_info, + ), + self.list_search_configs: gapic_v1.method.wrap_method( + self.list_search_configs, + default_timeout=None, + client_info=client_info, + ), + self.search_assets: gapic_v1.method.wrap_method( + self.search_assets, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + Union[ + warehouse.Asset, + Awaitable[warehouse.Asset] + ]]: + raise NotImplementedError() + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + Union[ + warehouse.Asset, + Awaitable[warehouse.Asset] + ]]: + raise NotImplementedError() + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + Union[ + warehouse.Asset, + Awaitable[warehouse.Asset] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + Union[ + warehouse.ListAssetsResponse, + Awaitable[warehouse.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + Union[ + warehouse.Corpus, + Awaitable[warehouse.Corpus] + ]]: + raise NotImplementedError() + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + Union[ + warehouse.Corpus, + Awaitable[warehouse.Corpus] + ]]: + raise NotImplementedError() + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + Union[ + warehouse.ListCorporaResponse, + Awaitable[warehouse.ListCorporaResponse] + ]]: + raise NotImplementedError() + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + Union[ + warehouse.DataSchema, + Awaitable[warehouse.DataSchema] + ]]: + raise NotImplementedError() + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + Union[ + warehouse.DataSchema, + Awaitable[warehouse.DataSchema] + ]]: + raise NotImplementedError() + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + Union[ + warehouse.DataSchema, + Awaitable[warehouse.DataSchema] + ]]: + raise NotImplementedError() + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + Union[ + warehouse.ListDataSchemasResponse, + Awaitable[warehouse.ListDataSchemasResponse] + ]]: + raise NotImplementedError() + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + Union[ + warehouse.Annotation, + Awaitable[warehouse.Annotation] + ]]: + raise NotImplementedError() + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + Union[ + warehouse.Annotation, + Awaitable[warehouse.Annotation] + ]]: + raise NotImplementedError() + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + Union[ + warehouse.ListAnnotationsResponse, + Awaitable[warehouse.ListAnnotationsResponse] + ]]: + raise NotImplementedError() + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + Union[ + warehouse.Annotation, + Awaitable[warehouse.Annotation] + ]]: + raise NotImplementedError() + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + Union[ + warehouse.IngestAssetResponse, + Awaitable[warehouse.IngestAssetResponse] + ]]: + raise NotImplementedError() + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + Union[ + warehouse.ClipAssetResponse, + Awaitable[warehouse.ClipAssetResponse] + ]]: + raise NotImplementedError() + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + Union[ + warehouse.GenerateHlsUriResponse, + Awaitable[warehouse.GenerateHlsUriResponse] + ]]: + raise NotImplementedError() + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + Union[ + warehouse.SearchConfig, + Awaitable[warehouse.SearchConfig] + ]]: + raise NotImplementedError() + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + Union[ + warehouse.SearchConfig, + Awaitable[warehouse.SearchConfig] + ]]: + raise NotImplementedError() + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + Union[ + warehouse.SearchConfig, + Awaitable[warehouse.SearchConfig] + ]]: + raise NotImplementedError() + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + Union[ + warehouse.ListSearchConfigsResponse, + Awaitable[warehouse.ListSearchConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + Union[ + warehouse.SearchAssetsResponse, + Awaitable[warehouse.SearchAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WarehouseTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/grpc.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/grpc.py new file mode 100644 index 000000000000..16550a0c549e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/grpc.py @@ -0,0 +1,1250 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import WarehouseTransport, DEFAULT_CLIENT_INFO + + +class WarehouseGrpcTransport(WarehouseTransport): + """gRPC backend transport for Warehouse. + + Service that manages media content + metadata for streaming. + + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + warehouse.Asset]: + r"""Return a callable for the create asset method over gRPC. + + Creates an asset inside corpus. + + Returns: + Callable[[~.CreateAssetRequest], + ~.Asset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['create_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateAsset', + request_serializer=warehouse.CreateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['create_asset'] + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + warehouse.Asset]: + r"""Return a callable for the update asset method over gRPC. + + Updates an asset inside corpus. + + Returns: + Callable[[~.UpdateAssetRequest], + ~.Asset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['update_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateAsset', + request_serializer=warehouse.UpdateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['update_asset'] + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + warehouse.Asset]: + r"""Return a callable for the get asset method over gRPC. + + Reads an asset inside corpus. + + Returns: + Callable[[~.GetAssetRequest], + ~.Asset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['get_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetAsset', + request_serializer=warehouse.GetAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['get_asset'] + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + warehouse.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an list of assets inside corpus. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListAssets', + request_serializer=warehouse.ListAssetsRequest.serialize, + response_deserializer=warehouse.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete asset method over gRPC. + + Deletes asset inside corpus. + + Returns: + Callable[[~.DeleteAssetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_asset' not in self._stubs: + self._stubs['delete_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteAsset', + request_serializer=warehouse.DeleteAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_asset'] + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + operations_pb2.Operation]: + r"""Return a callable for the create corpus method over gRPC. + + Creates a corpus inside a project. + + Returns: + Callable[[~.CreateCorpusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_corpus' not in self._stubs: + self._stubs['create_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateCorpus', + request_serializer=warehouse.CreateCorpusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_corpus'] + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + warehouse.Corpus]: + r"""Return a callable for the get corpus method over gRPC. + + Gets corpus details inside a project. + + Returns: + Callable[[~.GetCorpusRequest], + ~.Corpus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['get_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetCorpus', + request_serializer=warehouse.GetCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['get_corpus'] + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + warehouse.Corpus]: + r"""Return a callable for the update corpus method over gRPC. + + Updates a corpus in a project. + + Returns: + Callable[[~.UpdateCorpusRequest], + ~.Corpus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['update_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateCorpus', + request_serializer=warehouse.UpdateCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['update_corpus'] + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + warehouse.ListCorporaResponse]: + r"""Return a callable for the list corpora method over gRPC. + + Lists all corpora in a project. + + Returns: + Callable[[~.ListCorporaRequest], + ~.ListCorporaResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpora' not in self._stubs: + self._stubs['list_corpora'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListCorpora', + request_serializer=warehouse.ListCorporaRequest.serialize, + response_deserializer=warehouse.ListCorporaResponse.deserialize, + ) + return self._stubs['list_corpora'] + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete corpus method over gRPC. + + Deletes a corpus only if its empty. + Returns empty response. + + Returns: + Callable[[~.DeleteCorpusRequest], + ~.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_corpus' not in self._stubs: + self._stubs['delete_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteCorpus', + request_serializer=warehouse.DeleteCorpusRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_corpus'] + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + warehouse.DataSchema]: + r"""Return a callable for the create data schema method over gRPC. + + Creates data schema inside corpus. + + Returns: + Callable[[~.CreateDataSchemaRequest], + ~.DataSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['create_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateDataSchema', + request_serializer=warehouse.CreateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['create_data_schema'] + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + warehouse.DataSchema]: + r"""Return a callable for the update data schema method over gRPC. + + Updates data schema inside corpus. + + Returns: + Callable[[~.UpdateDataSchemaRequest], + ~.DataSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['update_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateDataSchema', + request_serializer=warehouse.UpdateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['update_data_schema'] + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + warehouse.DataSchema]: + r"""Return a callable for the get data schema method over gRPC. + + Gets data schema inside corpus. + + Returns: + Callable[[~.GetDataSchemaRequest], + ~.DataSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['get_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetDataSchema', + request_serializer=warehouse.GetDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['get_data_schema'] + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete data schema method over gRPC. + + Deletes data schema inside corpus. + + Returns: + Callable[[~.DeleteDataSchemaRequest], + ~.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_data_schema' not in self._stubs: + self._stubs['delete_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteDataSchema', + request_serializer=warehouse.DeleteDataSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_schema'] + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + warehouse.ListDataSchemasResponse]: + r"""Return a callable for the list data schemas method over gRPC. + + Lists a list of data schemas inside corpus. + + Returns: + Callable[[~.ListDataSchemasRequest], + ~.ListDataSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schemas' not in self._stubs: + self._stubs['list_data_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListDataSchemas', + request_serializer=warehouse.ListDataSchemasRequest.serialize, + response_deserializer=warehouse.ListDataSchemasResponse.deserialize, + ) + return self._stubs['list_data_schemas'] + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + warehouse.Annotation]: + r"""Return a callable for the create annotation method over gRPC. + + Creates annotation inside asset. + + Returns: + Callable[[~.CreateAnnotationRequest], + ~.Annotation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['create_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateAnnotation', + request_serializer=warehouse.CreateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['create_annotation'] + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + warehouse.Annotation]: + r"""Return a callable for the get annotation method over gRPC. + + Reads annotation inside asset. + + Returns: + Callable[[~.GetAnnotationRequest], + ~.Annotation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['get_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetAnnotation', + request_serializer=warehouse.GetAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['get_annotation'] + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + warehouse.ListAnnotationsResponse]: + r"""Return a callable for the list annotations method over gRPC. + + Lists a list of annotations inside asset. + + Returns: + Callable[[~.ListAnnotationsRequest], + ~.ListAnnotationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotations' not in self._stubs: + self._stubs['list_annotations'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListAnnotations', + request_serializer=warehouse.ListAnnotationsRequest.serialize, + response_deserializer=warehouse.ListAnnotationsResponse.deserialize, + ) + return self._stubs['list_annotations'] + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + warehouse.Annotation]: + r"""Return a callable for the update annotation method over gRPC. + + Updates annotation inside asset. + + Returns: + Callable[[~.UpdateAnnotationRequest], + ~.Annotation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['update_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateAnnotation', + request_serializer=warehouse.UpdateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['update_annotation'] + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete annotation method over gRPC. + + Deletes annotation inside asset. + + Returns: + Callable[[~.DeleteAnnotationRequest], + ~.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_annotation' not in self._stubs: + self._stubs['delete_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteAnnotation', + request_serializer=warehouse.DeleteAnnotationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotation'] + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + warehouse.IngestAssetResponse]: + r"""Return a callable for the ingest asset method over gRPC. + + Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + Returns: + Callable[[~.IngestAssetRequest], + ~.IngestAssetResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'ingest_asset' not in self._stubs: + self._stubs['ingest_asset'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.Warehouse/IngestAsset', + request_serializer=warehouse.IngestAssetRequest.serialize, + response_deserializer=warehouse.IngestAssetResponse.deserialize, + ) + return self._stubs['ingest_asset'] + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + warehouse.ClipAssetResponse]: + r"""Return a callable for the clip asset method over gRPC. + + Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + Returns: + Callable[[~.ClipAssetRequest], + ~.ClipAssetResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'clip_asset' not in self._stubs: + self._stubs['clip_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ClipAsset', + request_serializer=warehouse.ClipAssetRequest.serialize, + response_deserializer=warehouse.ClipAssetResponse.deserialize, + ) + return self._stubs['clip_asset'] + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + warehouse.GenerateHlsUriResponse]: + r"""Return a callable for the generate hls uri method over gRPC. + + Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + Returns: + Callable[[~.GenerateHlsUriRequest], + ~.GenerateHlsUriResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_hls_uri' not in self._stubs: + self._stubs['generate_hls_uri'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GenerateHlsUri', + request_serializer=warehouse.GenerateHlsUriRequest.serialize, + response_deserializer=warehouse.GenerateHlsUriResponse.deserialize, + ) + return self._stubs['generate_hls_uri'] + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + warehouse.SearchConfig]: + r"""Return a callable for the create search config method over gRPC. + + Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.CreateSearchConfigRequest], + ~.SearchConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['create_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateSearchConfig', + request_serializer=warehouse.CreateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['create_search_config'] + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + warehouse.SearchConfig]: + r"""Return a callable for the update search config method over gRPC. + + Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.UpdateSearchConfigRequest], + ~.SearchConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['update_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateSearchConfig', + request_serializer=warehouse.UpdateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['update_search_config'] + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + warehouse.SearchConfig]: + r"""Return a callable for the get search config method over gRPC. + + Gets a search configuration inside a corpus. + + Returns: + Callable[[~.GetSearchConfigRequest], + ~.SearchConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['get_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetSearchConfig', + request_serializer=warehouse.GetSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['get_search_config'] + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete search config method over gRPC. + + Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + Returns: + Callable[[~.DeleteSearchConfigRequest], + ~.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_search_config' not in self._stubs: + self._stubs['delete_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteSearchConfig', + request_serializer=warehouse.DeleteSearchConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_config'] + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + warehouse.ListSearchConfigsResponse]: + r"""Return a callable for the list search configs method over gRPC. + + Lists all search configurations inside a corpus. + + Returns: + Callable[[~.ListSearchConfigsRequest], + ~.ListSearchConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_configs' not in self._stubs: + self._stubs['list_search_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListSearchConfigs', + request_serializer=warehouse.ListSearchConfigsRequest.serialize, + response_deserializer=warehouse.ListSearchConfigsResponse.deserialize, + ) + return self._stubs['list_search_configs'] + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + warehouse.SearchAssetsResponse]: + r"""Return a callable for the search assets method over gRPC. + + Search media asset. + + Returns: + Callable[[~.SearchAssetsRequest], + ~.SearchAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_assets' not in self._stubs: + self._stubs['search_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/SearchAssets', + request_serializer=warehouse.SearchAssetsRequest.serialize, + response_deserializer=warehouse.SearchAssetsResponse.deserialize, + ) + return self._stubs['search_assets'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WarehouseGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/grpc_asyncio.py new file mode 100644 index 000000000000..11824532358d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/grpc_asyncio.py @@ -0,0 +1,1450 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.visionai_v1alpha1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import WarehouseTransport, DEFAULT_CLIENT_INFO +from .grpc import WarehouseGrpcTransport + + +class WarehouseGrpcAsyncIOTransport(WarehouseTransport): + """gRPC AsyncIO backend transport for Warehouse. + + Service that manages media content + metadata for streaming. + + 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 = 'visionai.googleapis.com', + credentials: Optional[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`. + 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 = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + Awaitable[warehouse.Asset]]: + r"""Return a callable for the create asset method over gRPC. + + Creates an asset inside corpus. + + Returns: + Callable[[~.CreateAssetRequest], + Awaitable[~.Asset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['create_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateAsset', + request_serializer=warehouse.CreateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['create_asset'] + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + Awaitable[warehouse.Asset]]: + r"""Return a callable for the update asset method over gRPC. + + Updates an asset inside corpus. + + Returns: + Callable[[~.UpdateAssetRequest], + Awaitable[~.Asset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['update_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateAsset', + request_serializer=warehouse.UpdateAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['update_asset'] + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + Awaitable[warehouse.Asset]]: + r"""Return a callable for the get asset method over gRPC. + + Reads an asset inside corpus. + + Returns: + Callable[[~.GetAssetRequest], + Awaitable[~.Asset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_asset' not in self._stubs: + self._stubs['get_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetAsset', + request_serializer=warehouse.GetAssetRequest.serialize, + response_deserializer=warehouse.Asset.deserialize, + ) + return self._stubs['get_asset'] + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + Awaitable[warehouse.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an list of assets inside corpus. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListAssets', + request_serializer=warehouse.ListAssetsRequest.serialize, + response_deserializer=warehouse.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete asset method over gRPC. + + Deletes asset inside corpus. + + Returns: + Callable[[~.DeleteAssetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_asset' not in self._stubs: + self._stubs['delete_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteAsset', + request_serializer=warehouse.DeleteAssetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_asset'] + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create corpus method over gRPC. + + Creates a corpus inside a project. + + Returns: + Callable[[~.CreateCorpusRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_corpus' not in self._stubs: + self._stubs['create_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateCorpus', + request_serializer=warehouse.CreateCorpusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_corpus'] + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + Awaitable[warehouse.Corpus]]: + r"""Return a callable for the get corpus method over gRPC. + + Gets corpus details inside a project. + + Returns: + Callable[[~.GetCorpusRequest], + Awaitable[~.Corpus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['get_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetCorpus', + request_serializer=warehouse.GetCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['get_corpus'] + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + Awaitable[warehouse.Corpus]]: + r"""Return a callable for the update corpus method over gRPC. + + Updates a corpus in a project. + + Returns: + Callable[[~.UpdateCorpusRequest], + Awaitable[~.Corpus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpus' not in self._stubs: + self._stubs['update_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateCorpus', + request_serializer=warehouse.UpdateCorpusRequest.serialize, + response_deserializer=warehouse.Corpus.deserialize, + ) + return self._stubs['update_corpus'] + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + Awaitable[warehouse.ListCorporaResponse]]: + r"""Return a callable for the list corpora method over gRPC. + + Lists all corpora in a project. + + Returns: + Callable[[~.ListCorporaRequest], + Awaitable[~.ListCorporaResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_corpora' not in self._stubs: + self._stubs['list_corpora'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListCorpora', + request_serializer=warehouse.ListCorporaRequest.serialize, + response_deserializer=warehouse.ListCorporaResponse.deserialize, + ) + return self._stubs['list_corpora'] + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete corpus method over gRPC. + + Deletes a corpus only if its empty. + Returns empty response. + + Returns: + Callable[[~.DeleteCorpusRequest], + 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_corpus' not in self._stubs: + self._stubs['delete_corpus'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteCorpus', + request_serializer=warehouse.DeleteCorpusRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_corpus'] + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + Awaitable[warehouse.DataSchema]]: + r"""Return a callable for the create data schema method over gRPC. + + Creates data schema inside corpus. + + Returns: + Callable[[~.CreateDataSchemaRequest], + Awaitable[~.DataSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['create_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateDataSchema', + request_serializer=warehouse.CreateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['create_data_schema'] + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + Awaitable[warehouse.DataSchema]]: + r"""Return a callable for the update data schema method over gRPC. + + Updates data schema inside corpus. + + Returns: + Callable[[~.UpdateDataSchemaRequest], + Awaitable[~.DataSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['update_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateDataSchema', + request_serializer=warehouse.UpdateDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['update_data_schema'] + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + Awaitable[warehouse.DataSchema]]: + r"""Return a callable for the get data schema method over gRPC. + + Gets data schema inside corpus. + + Returns: + Callable[[~.GetDataSchemaRequest], + Awaitable[~.DataSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schema' not in self._stubs: + self._stubs['get_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetDataSchema', + request_serializer=warehouse.GetDataSchemaRequest.serialize, + response_deserializer=warehouse.DataSchema.deserialize, + ) + return self._stubs['get_data_schema'] + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete data schema method over gRPC. + + Deletes data schema inside corpus. + + Returns: + Callable[[~.DeleteDataSchemaRequest], + 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_data_schema' not in self._stubs: + self._stubs['delete_data_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteDataSchema', + request_serializer=warehouse.DeleteDataSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_schema'] + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + Awaitable[warehouse.ListDataSchemasResponse]]: + r"""Return a callable for the list data schemas method over gRPC. + + Lists a list of data schemas inside corpus. + + Returns: + Callable[[~.ListDataSchemasRequest], + Awaitable[~.ListDataSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_schemas' not in self._stubs: + self._stubs['list_data_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListDataSchemas', + request_serializer=warehouse.ListDataSchemasRequest.serialize, + response_deserializer=warehouse.ListDataSchemasResponse.deserialize, + ) + return self._stubs['list_data_schemas'] + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + Awaitable[warehouse.Annotation]]: + r"""Return a callable for the create annotation method over gRPC. + + Creates annotation inside asset. + + Returns: + Callable[[~.CreateAnnotationRequest], + Awaitable[~.Annotation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['create_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateAnnotation', + request_serializer=warehouse.CreateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['create_annotation'] + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + Awaitable[warehouse.Annotation]]: + r"""Return a callable for the get annotation method over gRPC. + + Reads annotation inside asset. + + Returns: + Callable[[~.GetAnnotationRequest], + Awaitable[~.Annotation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['get_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetAnnotation', + request_serializer=warehouse.GetAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['get_annotation'] + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + Awaitable[warehouse.ListAnnotationsResponse]]: + r"""Return a callable for the list annotations method over gRPC. + + Lists a list of annotations inside asset. + + Returns: + Callable[[~.ListAnnotationsRequest], + Awaitable[~.ListAnnotationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotations' not in self._stubs: + self._stubs['list_annotations'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListAnnotations', + request_serializer=warehouse.ListAnnotationsRequest.serialize, + response_deserializer=warehouse.ListAnnotationsResponse.deserialize, + ) + return self._stubs['list_annotations'] + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + Awaitable[warehouse.Annotation]]: + r"""Return a callable for the update annotation method over gRPC. + + Updates annotation inside asset. + + Returns: + Callable[[~.UpdateAnnotationRequest], + Awaitable[~.Annotation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_annotation' not in self._stubs: + self._stubs['update_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateAnnotation', + request_serializer=warehouse.UpdateAnnotationRequest.serialize, + response_deserializer=warehouse.Annotation.deserialize, + ) + return self._stubs['update_annotation'] + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete annotation method over gRPC. + + Deletes annotation inside asset. + + Returns: + Callable[[~.DeleteAnnotationRequest], + 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_annotation' not in self._stubs: + self._stubs['delete_annotation'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteAnnotation', + request_serializer=warehouse.DeleteAnnotationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_annotation'] + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + Awaitable[warehouse.IngestAssetResponse]]: + r"""Return a callable for the ingest asset method over gRPC. + + Ingests data for the asset. It is not allowed to + ingest a data chunk which is already expired according + to TTL. This method is only available via the gRPC API + (not HTTP since bi-directional streaming is not + supported via HTTP). + + Returns: + Callable[[~.IngestAssetRequest], + Awaitable[~.IngestAssetResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'ingest_asset' not in self._stubs: + self._stubs['ingest_asset'] = self.grpc_channel.stream_stream( + '/google.cloud.visionai.v1alpha1.Warehouse/IngestAsset', + request_serializer=warehouse.IngestAssetRequest.serialize, + response_deserializer=warehouse.IngestAssetResponse.deserialize, + ) + return self._stubs['ingest_asset'] + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + Awaitable[warehouse.ClipAssetResponse]]: + r"""Return a callable for the clip asset method over gRPC. + + Generates clips for downloading. The api takes in a time range, + and generates a clip of the first content available after + start_time and before end_time, which may overflow beyond these + bounds. Returned clips are truncated if the total size of the + clips are larger than 100MB. + + Returns: + Callable[[~.ClipAssetRequest], + Awaitable[~.ClipAssetResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'clip_asset' not in self._stubs: + self._stubs['clip_asset'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ClipAsset', + request_serializer=warehouse.ClipAssetRequest.serialize, + response_deserializer=warehouse.ClipAssetResponse.deserialize, + ) + return self._stubs['clip_asset'] + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + Awaitable[warehouse.GenerateHlsUriResponse]]: + r"""Return a callable for the generate hls uri method over gRPC. + + Generates a uri for an HLS manifest. The api takes in + a collection of time ranges, and generates a URI for an + HLS manifest that covers all the requested time ranges. + + Returns: + Callable[[~.GenerateHlsUriRequest], + Awaitable[~.GenerateHlsUriResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_hls_uri' not in self._stubs: + self._stubs['generate_hls_uri'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GenerateHlsUri', + request_serializer=warehouse.GenerateHlsUriRequest.serialize, + response_deserializer=warehouse.GenerateHlsUriResponse.deserialize, + ) + return self._stubs['generate_hls_uri'] + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + Awaitable[warehouse.SearchConfig]]: + r"""Return a callable for the create search config method over gRPC. + + Creates a search configuration inside a corpus. + + Please follow the rules below to create a valid + CreateSearchConfigRequest. --- General Rules --- + + 1. Request.search_config_id must not be associated with an + existing SearchConfig. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.CreateSearchConfigRequest], + Awaitable[~.SearchConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['create_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/CreateSearchConfig', + request_serializer=warehouse.CreateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['create_search_config'] + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + Awaitable[warehouse.SearchConfig]]: + r"""Return a callable for the update search config method over gRPC. + + Updates a search configuration inside a corpus. + + Please follow the rules below to create a valid + UpdateSearchConfigRequest. --- General Rules --- + + 1. Request.search_configuration.name must already exist. + 2. Request must contain at least one non-empty + search_criteria_property or facet_property. + 3. mapped_fields must not be empty, and must map to existing UGA + keys. + 4. All mapped_fields must be of the same type. + 5. All mapped_fields must share the same granularity. + 6. All mapped_fields must share the same semantic SearchConfig + match options. For property-specific rules, please reference + the comments for FacetProperty and SearchCriteriaProperty. + + Returns: + Callable[[~.UpdateSearchConfigRequest], + Awaitable[~.SearchConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['update_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/UpdateSearchConfig', + request_serializer=warehouse.UpdateSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['update_search_config'] + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + Awaitable[warehouse.SearchConfig]]: + r"""Return a callable for the get search config method over gRPC. + + Gets a search configuration inside a corpus. + + Returns: + Callable[[~.GetSearchConfigRequest], + Awaitable[~.SearchConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_config' not in self._stubs: + self._stubs['get_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/GetSearchConfig', + request_serializer=warehouse.GetSearchConfigRequest.serialize, + response_deserializer=warehouse.SearchConfig.deserialize, + ) + return self._stubs['get_search_config'] + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete search config method over gRPC. + + Deletes a search configuration inside a corpus. + + For a DeleteSearchConfigRequest to be valid, + Request.search_configuration.name must already exist. + + Returns: + Callable[[~.DeleteSearchConfigRequest], + 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_search_config' not in self._stubs: + self._stubs['delete_search_config'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/DeleteSearchConfig', + request_serializer=warehouse.DeleteSearchConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_config'] + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + Awaitable[warehouse.ListSearchConfigsResponse]]: + r"""Return a callable for the list search configs method over gRPC. + + Lists all search configurations inside a corpus. + + Returns: + Callable[[~.ListSearchConfigsRequest], + Awaitable[~.ListSearchConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_search_configs' not in self._stubs: + self._stubs['list_search_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/ListSearchConfigs', + request_serializer=warehouse.ListSearchConfigsRequest.serialize, + response_deserializer=warehouse.ListSearchConfigsResponse.deserialize, + ) + return self._stubs['list_search_configs'] + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + Awaitable[warehouse.SearchAssetsResponse]]: + r"""Return a callable for the search assets method over gRPC. + + Search media asset. + + Returns: + Callable[[~.SearchAssetsRequest], + Awaitable[~.SearchAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_assets' not in self._stubs: + self._stubs['search_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.visionai.v1alpha1.Warehouse/SearchAssets', + request_serializer=warehouse.SearchAssetsRequest.serialize, + response_deserializer=warehouse.SearchAssetsResponse.deserialize, + ) + return self._stubs['search_assets'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_asset: gapic_v1.method_async.wrap_method( + self.create_asset, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_asset: gapic_v1.method_async.wrap_method( + self.update_asset, + default_timeout=None, + client_info=client_info, + ), + self.get_asset: gapic_v1.method_async.wrap_method( + self.get_asset, + default_timeout=None, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + default_timeout=None, + client_info=client_info, + ), + self.delete_asset: gapic_v1.method_async.wrap_method( + self.delete_asset, + default_timeout=None, + client_info=client_info, + ), + self.create_corpus: gapic_v1.method_async.wrap_method( + self.create_corpus, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_corpus: gapic_v1.method_async.wrap_method( + self.get_corpus, + default_timeout=None, + client_info=client_info, + ), + self.update_corpus: gapic_v1.method_async.wrap_method( + self.update_corpus, + default_timeout=None, + client_info=client_info, + ), + self.list_corpora: gapic_v1.method_async.wrap_method( + self.list_corpora, + default_timeout=None, + client_info=client_info, + ), + self.delete_corpus: gapic_v1.method_async.wrap_method( + self.delete_corpus, + default_timeout=None, + client_info=client_info, + ), + self.create_data_schema: gapic_v1.method_async.wrap_method( + self.create_data_schema, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_data_schema: gapic_v1.method_async.wrap_method( + self.update_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.get_data_schema: gapic_v1.method_async.wrap_method( + self.get_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_schema: gapic_v1.method_async.wrap_method( + self.delete_data_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_data_schemas: gapic_v1.method_async.wrap_method( + self.list_data_schemas, + default_timeout=None, + client_info=client_info, + ), + self.create_annotation: gapic_v1.method_async.wrap_method( + self.create_annotation, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.get_annotation: gapic_v1.method_async.wrap_method( + self.get_annotation, + default_timeout=None, + client_info=client_info, + ), + self.list_annotations: gapic_v1.method_async.wrap_method( + self.list_annotations, + default_timeout=None, + client_info=client_info, + ), + self.update_annotation: gapic_v1.method_async.wrap_method( + self.update_annotation, + default_timeout=None, + client_info=client_info, + ), + self.delete_annotation: gapic_v1.method_async.wrap_method( + self.delete_annotation, + default_timeout=None, + client_info=client_info, + ), + self.ingest_asset: gapic_v1.method_async.wrap_method( + self.ingest_asset, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=2.5, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.clip_asset: gapic_v1.method_async.wrap_method( + self.clip_asset, + default_timeout=None, + client_info=client_info, + ), + self.generate_hls_uri: gapic_v1.method_async.wrap_method( + self.generate_hls_uri, + default_timeout=None, + client_info=client_info, + ), + self.create_search_config: gapic_v1.method_async.wrap_method( + self.create_search_config, + default_timeout=None, + client_info=client_info, + ), + self.update_search_config: gapic_v1.method_async.wrap_method( + self.update_search_config, + default_timeout=None, + client_info=client_info, + ), + self.get_search_config: gapic_v1.method_async.wrap_method( + self.get_search_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_config: gapic_v1.method_async.wrap_method( + self.delete_search_config, + default_timeout=None, + client_info=client_info, + ), + self.list_search_configs: gapic_v1.method_async.wrap_method( + self.list_search_configs, + default_timeout=None, + client_info=client_info, + ), + self.search_assets: gapic_v1.method_async.wrap_method( + self.search_assets, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'WarehouseGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/rest.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/rest.py new file mode 100644 index 000000000000..d57754aa2c56 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/services/warehouse/transports/rest.py @@ -0,0 +1,4245 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.visionai_v1alpha1.types import warehouse +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import WarehouseTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class WarehouseRestInterceptor: + """Interceptor for Warehouse. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the WarehouseRestTransport. + + .. code-block:: python + class MyCustomWarehouseInterceptor(WarehouseRestInterceptor): + def pre_clip_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_clip_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_annotation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_data_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_search_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_generate_hls_uri(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_hls_uri(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_annotation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_search_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_annotations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_annotations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_corpora(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_corpora(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_schemas(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_schemas(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_search_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_search_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_annotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_annotation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_asset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_asset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_search_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_search_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WarehouseRestTransport(interceptor=MyCustomWarehouseInterceptor()) + client = WarehouseClient(transport=transport) + + + """ + def pre_clip_asset(self, request: warehouse.ClipAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ClipAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for clip_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_clip_asset(self, response: warehouse.ClipAssetResponse) -> warehouse.ClipAssetResponse: + """Post-rpc interceptor for clip_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_annotation(self, request: warehouse.CreateAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_annotation(self, response: warehouse.Annotation) -> warehouse.Annotation: + """Post-rpc interceptor for create_annotation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_asset(self, request: warehouse.CreateAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_asset(self, response: warehouse.Asset) -> warehouse.Asset: + """Post-rpc interceptor for create_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_corpus(self, request: warehouse.CreateCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_corpus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_corpus + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_data_schema(self, request: warehouse.CreateDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_data_schema(self, response: warehouse.DataSchema) -> warehouse.DataSchema: + """Post-rpc interceptor for create_data_schema + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_create_search_config(self, request: warehouse.CreateSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.CreateSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_create_search_config(self, response: warehouse.SearchConfig) -> warehouse.SearchConfig: + """Post-rpc interceptor for create_search_config + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_annotation(self, request: warehouse.DeleteAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_delete_asset(self, request: warehouse.DeleteAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_delete_asset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_corpus(self, request: warehouse.DeleteCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_delete_data_schema(self, request: warehouse.DeleteDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_delete_search_config(self, request: warehouse.DeleteSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.DeleteSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def pre_generate_hls_uri(self, request: warehouse.GenerateHlsUriRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GenerateHlsUriRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_hls_uri + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_generate_hls_uri(self, response: warehouse.GenerateHlsUriResponse) -> warehouse.GenerateHlsUriResponse: + """Post-rpc interceptor for generate_hls_uri + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_annotation(self, request: warehouse.GetAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_annotation(self, response: warehouse.Annotation) -> warehouse.Annotation: + """Post-rpc interceptor for get_annotation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_asset(self, request: warehouse.GetAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_asset(self, response: warehouse.Asset) -> warehouse.Asset: + """Post-rpc interceptor for get_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_corpus(self, request: warehouse.GetCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_corpus(self, response: warehouse.Corpus) -> warehouse.Corpus: + """Post-rpc interceptor for get_corpus + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_data_schema(self, request: warehouse.GetDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_data_schema(self, response: warehouse.DataSchema) -> warehouse.DataSchema: + """Post-rpc interceptor for get_data_schema + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_search_config(self, request: warehouse.GetSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.GetSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_search_config(self, response: warehouse.SearchConfig) -> warehouse.SearchConfig: + """Post-rpc interceptor for get_search_config + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_annotations(self, request: warehouse.ListAnnotationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListAnnotationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_annotations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_annotations(self, response: warehouse.ListAnnotationsResponse) -> warehouse.ListAnnotationsResponse: + """Post-rpc interceptor for list_annotations + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: warehouse.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_assets(self, response: warehouse.ListAssetsResponse) -> warehouse.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_corpora(self, request: warehouse.ListCorporaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListCorporaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_corpora + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_corpora(self, response: warehouse.ListCorporaResponse) -> warehouse.ListCorporaResponse: + """Post-rpc interceptor for list_corpora + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_data_schemas(self, request: warehouse.ListDataSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListDataSchemasRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_data_schemas + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_data_schemas(self, response: warehouse.ListDataSchemasResponse) -> warehouse.ListDataSchemasResponse: + """Post-rpc interceptor for list_data_schemas + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_search_configs(self, request: warehouse.ListSearchConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.ListSearchConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_search_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_search_configs(self, response: warehouse.ListSearchConfigsResponse) -> warehouse.ListSearchConfigsResponse: + """Post-rpc interceptor for list_search_configs + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_search_assets(self, request: warehouse.SearchAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.SearchAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_search_assets(self, response: warehouse.SearchAssetsResponse) -> warehouse.SearchAssetsResponse: + """Post-rpc interceptor for search_assets + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_annotation(self, request: warehouse.UpdateAnnotationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateAnnotationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_annotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_annotation(self, response: warehouse.Annotation) -> warehouse.Annotation: + """Post-rpc interceptor for update_annotation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_asset(self, request: warehouse.UpdateAssetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateAssetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_asset + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_asset(self, response: warehouse.Asset) -> warehouse.Asset: + """Post-rpc interceptor for update_asset + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_corpus(self, request: warehouse.UpdateCorpusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateCorpusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_corpus(self, response: warehouse.Corpus) -> warehouse.Corpus: + """Post-rpc interceptor for update_corpus + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_data_schema(self, request: warehouse.UpdateDataSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateDataSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_data_schema(self, response: warehouse.DataSchema) -> warehouse.DataSchema: + """Post-rpc interceptor for update_data_schema + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_update_search_config(self, request: warehouse.UpdateSearchConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[warehouse.UpdateSearchConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_search_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_update_search_config(self, response: warehouse.SearchConfig) -> warehouse.SearchConfig: + """Post-rpc interceptor for update_search_config + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Warehouse server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Warehouse server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WarehouseRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WarehouseRestInterceptor + + +class WarehouseRestTransport(WarehouseTransport): + """REST backend transport for Warehouse. + + Service that manages media content + metadata for streaming. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'visionai.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[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, + url_scheme: str = 'https', + interceptor: Optional[WarehouseRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'visionai.googleapis.com'). + 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or WarehouseRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _ClipAsset(WarehouseRestStub): + def __hash__(self): + return hash("ClipAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ClipAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ClipAssetResponse: + r"""Call the clip asset method over HTTP. + + Args: + request (~.warehouse.ClipAssetRequest): + The request object. Request message for ClipAsset API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ClipAssetResponse: + Response message for ClipAsset API. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*}:clip', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_clip_asset(request, metadata) + pb_request = warehouse.ClipAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ClipAssetResponse() + pb_resp = warehouse.ClipAssetResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_clip_asset(resp) + return resp + + class _CreateAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("CreateAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Annotation: + r"""Call the create annotation method over HTTP. + + Args: + request (~.warehouse.CreateAnnotationRequest): + The request object. Request message for CreateAnnotation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations', + 'body': 'annotation', + }, + ] + request, metadata = self._interceptor.pre_create_annotation(request, metadata) + pb_request = warehouse.CreateAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Annotation() + pb_resp = warehouse.Annotation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_annotation(resp) + return resp + + class _CreateAsset(WarehouseRestStub): + def __hash__(self): + return hash("CreateAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Asset: + r"""Call the create asset method over HTTP. + + Args: + request (~.warehouse.CreateAssetRequest): + The request object. Request message for + CreateAssetRequest. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*}/assets', + 'body': 'asset', + }, + ] + request, metadata = self._interceptor.pre_create_asset(request, metadata) + pb_request = warehouse.CreateAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Asset() + pb_resp = warehouse.Asset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_asset(resp) + return resp + + class _CreateCorpus(WarehouseRestStub): + def __hash__(self): + return hash("CreateCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create corpus method over HTTP. + + Args: + request (~.warehouse.CreateCorpusRequest): + The request object. Request message of CreateCorpus API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/corpora', + 'body': 'corpus', + }, + ] + request, metadata = self._interceptor.pre_create_corpus(request, metadata) + pb_request = warehouse.CreateCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_corpus(resp) + return resp + + class _CreateDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("CreateDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.DataSchema: + r"""Call the create data schema method over HTTP. + + Args: + request (~.warehouse.CreateDataSchemaRequest): + The request object. Request message for CreateDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*}/dataSchemas', + 'body': 'data_schema', + }, + ] + request, metadata = self._interceptor.pre_create_data_schema(request, metadata) + pb_request = warehouse.CreateDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.DataSchema() + pb_resp = warehouse.DataSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_data_schema(resp) + return resp + + class _CreateSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("CreateSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "searchConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.CreateSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchConfig: + r"""Call the create search config method over HTTP. + + Args: + request (~.warehouse.CreateSearchConfigRequest): + The request object. Request message for + CreateSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*}/searchConfigs', + 'body': 'search_config', + }, + ] + request, metadata = self._interceptor.pre_create_search_config(request, metadata) + pb_request = warehouse.CreateSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchConfig() + pb_resp = warehouse.SearchConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_search_config(resp) + return resp + + class _DeleteAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("DeleteAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete annotation method over HTTP. + + Args: + request (~.warehouse.DeleteAnnotationRequest): + The request object. Request message for DeleteAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_annotation(request, metadata) + pb_request = warehouse.DeleteAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteAsset(WarehouseRestStub): + def __hash__(self): + return hash("DeleteAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete asset method over HTTP. + + Args: + request (~.warehouse.DeleteAssetRequest): + The request object. Request message for DeleteAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_asset(request, metadata) + pb_request = warehouse.DeleteAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_asset(resp) + return resp + + class _DeleteCorpus(WarehouseRestStub): + def __hash__(self): + return hash("DeleteCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete corpus method over HTTP. + + Args: + request (~.warehouse.DeleteCorpusRequest): + The request object. Request message for DeleteCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_corpus(request, metadata) + pb_request = warehouse.DeleteCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("DeleteDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete data schema method over HTTP. + + Args: + request (~.warehouse.DeleteDataSchemaRequest): + The request object. Request message for DeleteDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_data_schema(request, metadata) + pb_request = warehouse.DeleteDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("DeleteSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.DeleteSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete search config method over HTTP. + + Args: + request (~.warehouse.DeleteSearchConfigRequest): + The request object. Request message for + DeleteSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_search_config(request, metadata) + pb_request = warehouse.DeleteSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GenerateHlsUri(WarehouseRestStub): + def __hash__(self): + return hash("GenerateHlsUri") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GenerateHlsUriRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.GenerateHlsUriResponse: + r"""Call the generate hls uri method over HTTP. + + Args: + request (~.warehouse.GenerateHlsUriRequest): + The request object. Request message for GenerateHlsUri + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.GenerateHlsUriResponse: + Response message for GenerateHlsUri + API. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*}:generateHlsUri', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_hls_uri(request, metadata) + pb_request = warehouse.GenerateHlsUriRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.GenerateHlsUriResponse() + pb_resp = warehouse.GenerateHlsUriResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_hls_uri(resp) + return resp + + class _GetAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("GetAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Annotation: + r"""Call the get annotation method over HTTP. + + Args: + request (~.warehouse.GetAnnotationRequest): + The request object. Request message for GetAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_annotation(request, metadata) + pb_request = warehouse.GetAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Annotation() + pb_resp = warehouse.Annotation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_annotation(resp) + return resp + + class _GetAsset(WarehouseRestStub): + def __hash__(self): + return hash("GetAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Asset: + r"""Call the get asset method over HTTP. + + Args: + request (~.warehouse.GetAssetRequest): + The request object. Request message for GetAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*}', + }, + ] + request, metadata = self._interceptor.pre_get_asset(request, metadata) + pb_request = warehouse.GetAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Asset() + pb_resp = warehouse.Asset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_asset(resp) + return resp + + class _GetCorpus(WarehouseRestStub): + def __hash__(self): + return hash("GetCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Corpus: + r"""Call the get corpus method over HTTP. + + Args: + request (~.warehouse.GetCorpusRequest): + The request object. Request message for GetCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Corpus: + Corpus is a set of video contents for + management. Within a corpus, videos + share the same data schema. Search is + also restricted within a single corpus. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*}', + }, + ] + request, metadata = self._interceptor.pre_get_corpus(request, metadata) + pb_request = warehouse.GetCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Corpus() + pb_resp = warehouse.Corpus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_corpus(resp) + return resp + + class _GetDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("GetDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.DataSchema: + r"""Call the get data schema method over HTTP. + + Args: + request (~.warehouse.GetDataSchemaRequest): + The request object. Request message for GetDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}', + }, + ] + request, metadata = self._interceptor.pre_get_data_schema(request, metadata) + pb_request = warehouse.GetDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.DataSchema() + pb_resp = warehouse.DataSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_schema(resp) + return resp + + class _GetSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("GetSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.GetSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchConfig: + r"""Call the get search config method over HTTP. + + Args: + request (~.warehouse.GetSearchConfigRequest): + The request object. Request message for GetSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_search_config(request, metadata) + pb_request = warehouse.GetSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchConfig() + pb_resp = warehouse.SearchConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_search_config(resp) + return resp + + class _IngestAsset(WarehouseRestStub): + def __hash__(self): + return hash("IngestAsset") + + def __call__(self, + request: warehouse.IngestAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method IngestAsset is not available over REST transport" + ) + class _ListAnnotations(WarehouseRestStub): + def __hash__(self): + return hash("ListAnnotations") + + def __call__(self, + request: warehouse.ListAnnotationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListAnnotationsResponse: + r"""Call the list annotations method over HTTP. + + Args: + request (~.warehouse.ListAnnotationsRequest): + The request object. Request message for GetAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListAnnotationsResponse: + Request message for ListAnnotations + API. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations', + }, + ] + request, metadata = self._interceptor.pre_list_annotations(request, metadata) + pb_request = warehouse.ListAnnotationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListAnnotationsResponse() + pb_resp = warehouse.ListAnnotationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_annotations(resp) + return resp + + class _ListAssets(WarehouseRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.warehouse.ListAssetsRequest): + The request object. Request message for ListAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListAssetsResponse: + Response message for ListAssets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = warehouse.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListAssetsResponse() + pb_resp = warehouse.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListCorpora(WarehouseRestStub): + def __hash__(self): + return hash("ListCorpora") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListCorporaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListCorporaResponse: + r"""Call the list corpora method over HTTP. + + Args: + request (~.warehouse.ListCorporaRequest): + The request object. Request message for ListCorpora. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListCorporaResponse: + Response message for ListCorpora. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/corpora', + }, + ] + request, metadata = self._interceptor.pre_list_corpora(request, metadata) + pb_request = warehouse.ListCorporaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListCorporaResponse() + pb_resp = warehouse.ListCorporaResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_corpora(resp) + return resp + + class _ListDataSchemas(WarehouseRestStub): + def __hash__(self): + return hash("ListDataSchemas") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListDataSchemasRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListDataSchemasResponse: + r"""Call the list data schemas method over HTTP. + + Args: + request (~.warehouse.ListDataSchemasRequest): + The request object. Request message for ListDataSchemas. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListDataSchemasResponse: + Response message for ListDataSchemas. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*}/dataSchemas', + }, + ] + request, metadata = self._interceptor.pre_list_data_schemas(request, metadata) + pb_request = warehouse.ListDataSchemasRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListDataSchemasResponse() + pb_resp = warehouse.ListDataSchemasResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_data_schemas(resp) + return resp + + class _ListSearchConfigs(WarehouseRestStub): + def __hash__(self): + return hash("ListSearchConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.ListSearchConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.ListSearchConfigsResponse: + r"""Call the list search configs method over HTTP. + + Args: + request (~.warehouse.ListSearchConfigsRequest): + The request object. Request message for + ListSearchConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.ListSearchConfigsResponse: + Response message for + ListSearchConfigs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*/corpora/*}/searchConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_search_configs(request, metadata) + pb_request = warehouse.ListSearchConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.ListSearchConfigsResponse() + pb_resp = warehouse.ListSearchConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_search_configs(resp) + return resp + + class _SearchAssets(WarehouseRestStub): + def __hash__(self): + return hash("SearchAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.SearchAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchAssetsResponse: + r"""Call the search assets method over HTTP. + + Args: + request (~.warehouse.SearchAssetsRequest): + The request object. Request message for SearchAssets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchAssetsResponse: + Response message for SearchAssets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{corpus=projects/*/locations/*/corpora/*}:searchAssets', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search_assets(request, metadata) + pb_request = warehouse.SearchAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchAssetsResponse() + pb_resp = warehouse.SearchAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_assets(resp) + return resp + + class _UpdateAnnotation(WarehouseRestStub): + def __hash__(self): + return hash("UpdateAnnotation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateAnnotationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Annotation: + r"""Call the update annotation method over HTTP. + + Args: + request (~.warehouse.UpdateAnnotationRequest): + The request object. Request message for UpdateAnnotation + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Annotation: + An annotation is a resource in asset. + It represents a key-value mapping of + content in asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{annotation.name=projects/*/locations/*/corpora/*/assets/*/annotations/*}', + 'body': 'annotation', + }, + ] + request, metadata = self._interceptor.pre_update_annotation(request, metadata) + pb_request = warehouse.UpdateAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Annotation() + pb_resp = warehouse.Annotation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_annotation(resp) + return resp + + class _UpdateAsset(WarehouseRestStub): + def __hash__(self): + return hash("UpdateAsset") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateAssetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Asset: + r"""Call the update asset method over HTTP. + + Args: + request (~.warehouse.UpdateAssetRequest): + The request object. Response message for UpdateAsset. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Asset: + An asset is a resource in corpus. It + represents a media object inside corpus, + contains metadata and another resource + annotation. Different feature could be + applied to the asset to generate + annotations. User could specified + annotation related to the target asset. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{asset.name=projects/*/locations/*/corpora/*/assets/*}', + 'body': 'asset', + }, + ] + request, metadata = self._interceptor.pre_update_asset(request, metadata) + pb_request = warehouse.UpdateAssetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Asset() + pb_resp = warehouse.Asset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_asset(resp) + return resp + + class _UpdateCorpus(WarehouseRestStub): + def __hash__(self): + return hash("UpdateCorpus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateCorpusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.Corpus: + r"""Call the update corpus method over HTTP. + + Args: + request (~.warehouse.UpdateCorpusRequest): + The request object. Request message for UpdateCorpus. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.Corpus: + Corpus is a set of video contents for + management. Within a corpus, videos + share the same data schema. Search is + also restricted within a single corpus. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{corpus.name=projects/*/locations/*/corpora/*}', + 'body': 'corpus', + }, + ] + request, metadata = self._interceptor.pre_update_corpus(request, metadata) + pb_request = warehouse.UpdateCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.Corpus() + pb_resp = warehouse.Corpus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_corpus(resp) + return resp + + class _UpdateDataSchema(WarehouseRestStub): + def __hash__(self): + return hash("UpdateDataSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateDataSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.DataSchema: + r"""Call the update data schema method over HTTP. + + Args: + request (~.warehouse.UpdateDataSchemaRequest): + The request object. Request message for UpdateDataSchema. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.DataSchema: + Data schema indicates how the user + specified annotation is interpreted in + the system. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{data_schema.name=projects/*/locations/*/corpora/*/dataSchemas/*}', + 'body': 'data_schema', + }, + ] + request, metadata = self._interceptor.pre_update_data_schema(request, metadata) + pb_request = warehouse.UpdateDataSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.DataSchema() + pb_resp = warehouse.DataSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_schema(resp) + return resp + + class _UpdateSearchConfig(WarehouseRestStub): + def __hash__(self): + return hash("UpdateSearchConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: warehouse.UpdateSearchConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> warehouse.SearchConfig: + r"""Call the update search config method over HTTP. + + Args: + request (~.warehouse.UpdateSearchConfigRequest): + The request object. Request message for + UpdateSearchConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.warehouse.SearchConfig: + SearchConfig stores different + properties that will affect search + behaviors and search results. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{search_config.name=projects/*/locations/*/corpora/*/searchConfigs/*}', + 'body': 'search_config', + }, + ] + request, metadata = self._interceptor.pre_update_search_config(request, metadata) + pb_request = warehouse.UpdateSearchConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = warehouse.SearchConfig() + pb_resp = warehouse.SearchConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_search_config(resp) + return resp + + @property + def clip_asset(self) -> Callable[ + [warehouse.ClipAssetRequest], + warehouse.ClipAssetResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ClipAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_annotation(self) -> Callable[ + [warehouse.CreateAnnotationRequest], + warehouse.Annotation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_asset(self) -> Callable[ + [warehouse.CreateAssetRequest], + warehouse.Asset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_corpus(self) -> Callable[ + [warehouse.CreateCorpusRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_data_schema(self) -> Callable[ + [warehouse.CreateDataSchemaRequest], + warehouse.DataSchema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_search_config(self) -> Callable[ + [warehouse.CreateSearchConfigRequest], + warehouse.SearchConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_annotation(self) -> Callable[ + [warehouse.DeleteAnnotationRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_asset(self) -> Callable[ + [warehouse.DeleteAssetRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_corpus(self) -> Callable[ + [warehouse.DeleteCorpusRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_data_schema(self) -> Callable[ + [warehouse.DeleteDataSchemaRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_search_config(self) -> Callable[ + [warehouse.DeleteSearchConfigRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_hls_uri(self) -> Callable[ + [warehouse.GenerateHlsUriRequest], + warehouse.GenerateHlsUriResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateHlsUri(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_annotation(self) -> Callable[ + [warehouse.GetAnnotationRequest], + warehouse.Annotation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_asset(self) -> Callable[ + [warehouse.GetAssetRequest], + warehouse.Asset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_corpus(self) -> Callable[ + [warehouse.GetCorpusRequest], + warehouse.Corpus]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_schema(self) -> Callable[ + [warehouse.GetDataSchemaRequest], + warehouse.DataSchema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_search_config(self) -> Callable[ + [warehouse.GetSearchConfigRequest], + warehouse.SearchConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def ingest_asset(self) -> Callable[ + [warehouse.IngestAssetRequest], + warehouse.IngestAssetResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._IngestAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_annotations(self) -> Callable[ + [warehouse.ListAnnotationsRequest], + warehouse.ListAnnotationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAnnotations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [warehouse.ListAssetsRequest], + warehouse.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_corpora(self) -> Callable[ + [warehouse.ListCorporaRequest], + warehouse.ListCorporaResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCorpora(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_data_schemas(self) -> Callable[ + [warehouse.ListDataSchemasRequest], + warehouse.ListDataSchemasResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDataSchemas(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_search_configs(self) -> Callable[ + [warehouse.ListSearchConfigsRequest], + warehouse.ListSearchConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSearchConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_assets(self) -> Callable[ + [warehouse.SearchAssetsRequest], + warehouse.SearchAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_annotation(self) -> Callable[ + [warehouse.UpdateAnnotationRequest], + warehouse.Annotation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAnnotation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_asset(self) -> Callable[ + [warehouse.UpdateAssetRequest], + warehouse.Asset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAsset(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_corpus(self) -> Callable[ + [warehouse.UpdateCorpusRequest], + warehouse.Corpus]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_schema(self) -> Callable[ + [warehouse.UpdateDataSchemaRequest], + warehouse.DataSchema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDataSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_search_config(self) -> Callable[ + [warehouse.UpdateSearchConfigRequest], + warehouse.SearchConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSearchConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(WarehouseRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(WarehouseRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(WarehouseRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(WarehouseRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(WarehouseRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/streams/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/events/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/series/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/operators/*/versions/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clusters/*/analyses/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(WarehouseRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(WarehouseRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(WarehouseRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/warehouseOperations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(WarehouseRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WarehouseRestTransport', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/__init__.py new file mode 100644 index 000000000000..7f0e235ee7c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/__init__.py @@ -0,0 +1,498 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .annotations import ( + AppPlatformCloudFunctionRequest, + AppPlatformCloudFunctionResponse, + AppPlatformEventBody, + AppPlatformMetadata, + ClassificationPredictionResult, + ImageObjectDetectionPredictionResult, + ImageSegmentationPredictionResult, + NormalizedPolygon, + NormalizedPolyline, + NormalizedVertex, + ObjectDetectionPredictionResult, + OccupancyCountingPredictionResult, + PersonalProtectiveEquipmentDetectionOutput, + StreamAnnotation, + StreamAnnotations, + VideoActionRecognitionPredictionResult, + VideoClassificationPredictionResult, + VideoObjectTrackingPredictionResult, + StreamAnnotationType, +) +from .common import ( + Cluster, + GcsSource, + OperationMetadata, +) +from .lva import ( + AnalysisDefinition, + AnalyzerDefinition, + AttributeValue, +) +from .lva_resources import ( + Analysis, +) +from .lva_service import ( + CreateAnalysisRequest, + DeleteAnalysisRequest, + GetAnalysisRequest, + ListAnalysesRequest, + ListAnalysesResponse, + UpdateAnalysisRequest, +) +from .platform import ( + AddApplicationStreamInputRequest, + AddApplicationStreamInputResponse, + AIEnabledDevicesInputConfig, + Application, + ApplicationConfigs, + ApplicationInstance, + ApplicationNodeAnnotation, + ApplicationStreamInput, + AutoscalingMetricSpec, + BigQueryConfig, + CreateApplicationInstancesRequest, + CreateApplicationInstancesResponse, + CreateApplicationRequest, + CreateDraftRequest, + CreateProcessorRequest, + CustomProcessorSourceInfo, + DedicatedResources, + DeleteApplicationInstancesRequest, + DeleteApplicationInstancesResponse, + DeleteApplicationRequest, + DeleteDraftRequest, + DeleteProcessorRequest, + DeployApplicationRequest, + DeployApplicationResponse, + Draft, + GeneralObjectDetectionConfig, + GetApplicationRequest, + GetDraftRequest, + GetInstanceRequest, + GetProcessorRequest, + Instance, + ListApplicationsRequest, + ListApplicationsResponse, + ListDraftsRequest, + ListDraftsResponse, + ListInstancesRequest, + ListInstancesResponse, + ListPrebuiltProcessorsRequest, + ListPrebuiltProcessorsResponse, + ListProcessorsRequest, + ListProcessorsResponse, + MachineSpec, + MediaWarehouseConfig, + Node, + OccupancyCountConfig, + PersonalProtectiveEquipmentDetectionConfig, + PersonBlurConfig, + PersonVehicleDetectionConfig, + Processor, + ProcessorConfig, + ProcessorIOSpec, + RemoveApplicationStreamInputRequest, + RemoveApplicationStreamInputResponse, + ResourceAnnotations, + StreamWithAnnotation, + UndeployApplicationRequest, + UndeployApplicationResponse, + UpdateApplicationInstancesRequest, + UpdateApplicationInstancesResponse, + UpdateApplicationRequest, + UpdateApplicationStreamInputRequest, + UpdateApplicationStreamInputResponse, + UpdateDraftRequest, + UpdateProcessorRequest, + VertexAutoMLVideoConfig, + VertexAutoMLVisionConfig, + VertexCustomConfig, + VideoStreamInputConfig, + AcceleratorType, + ModelType, +) +from .streaming_resources import ( + GstreamerBufferDescriptor, + Packet, + PacketHeader, + PacketType, + RawImageDescriptor, + SeriesMetadata, + ServerMetadata, +) +from .streaming_service import ( + AcquireLeaseRequest, + CommitRequest, + ControlledMode, + EagerMode, + EventUpdate, + Lease, + ReceiveEventsControlResponse, + ReceiveEventsRequest, + ReceiveEventsResponse, + ReceivePacketsControlResponse, + ReceivePacketsRequest, + ReceivePacketsResponse, + ReleaseLeaseRequest, + ReleaseLeaseResponse, + RenewLeaseRequest, + RequestMetadata, + SendPacketsRequest, + SendPacketsResponse, + LeaseType, +) +from .streams_resources import ( + Channel, + Event, + Series, + Stream, +) +from .streams_service import ( + CreateClusterRequest, + CreateEventRequest, + CreateSeriesRequest, + CreateStreamRequest, + DeleteClusterRequest, + DeleteEventRequest, + DeleteSeriesRequest, + DeleteStreamRequest, + GenerateStreamHlsTokenRequest, + GenerateStreamHlsTokenResponse, + GetClusterRequest, + GetEventRequest, + GetSeriesRequest, + GetStreamRequest, + GetStreamThumbnailResponse, + ListClustersRequest, + ListClustersResponse, + ListEventsRequest, + ListEventsResponse, + ListSeriesRequest, + ListSeriesResponse, + ListStreamsRequest, + ListStreamsResponse, + MaterializeChannelRequest, + UpdateClusterRequest, + UpdateEventRequest, + UpdateSeriesRequest, + UpdateStreamRequest, +) +from .warehouse import ( + Annotation, + AnnotationMatchingResult, + AnnotationValue, + Asset, + BoolValue, + CircleArea, + ClipAssetRequest, + ClipAssetResponse, + Corpus, + CreateAnnotationRequest, + CreateAssetRequest, + CreateCorpusMetadata, + CreateCorpusRequest, + CreateDataSchemaRequest, + CreateSearchConfigRequest, + Criteria, + DataSchema, + DataSchemaDetails, + DateTimeRange, + DateTimeRangeArray, + DeleteAnnotationRequest, + DeleteAssetMetadata, + DeleteAssetRequest, + DeleteCorpusRequest, + DeleteDataSchemaRequest, + DeleteSearchConfigRequest, + FacetBucket, + FacetGroup, + FacetProperty, + FacetValue, + FloatRange, + FloatRangeArray, + GenerateHlsUriRequest, + GenerateHlsUriResponse, + GeoCoordinate, + GeoLocationArray, + GetAnnotationRequest, + GetAssetRequest, + GetCorpusRequest, + GetDataSchemaRequest, + GetSearchConfigRequest, + IngestAssetRequest, + IngestAssetResponse, + IntRange, + IntRangeArray, + ListAnnotationsRequest, + ListAnnotationsResponse, + ListAssetsRequest, + ListAssetsResponse, + ListCorporaRequest, + ListCorporaResponse, + ListDataSchemasRequest, + ListDataSchemasResponse, + ListSearchConfigsRequest, + ListSearchConfigsResponse, + Partition, + SearchAssetsRequest, + SearchAssetsResponse, + SearchConfig, + SearchCriteriaProperty, + SearchResultItem, + StringArray, + UpdateAnnotationRequest, + UpdateAssetRequest, + UpdateCorpusRequest, + UpdateDataSchemaRequest, + UpdateSearchConfigRequest, + UserSpecifiedAnnotation, + FacetBucketType, +) + +__all__ = ( + 'AppPlatformCloudFunctionRequest', + 'AppPlatformCloudFunctionResponse', + 'AppPlatformEventBody', + 'AppPlatformMetadata', + 'ClassificationPredictionResult', + 'ImageObjectDetectionPredictionResult', + 'ImageSegmentationPredictionResult', + 'NormalizedPolygon', + 'NormalizedPolyline', + 'NormalizedVertex', + 'ObjectDetectionPredictionResult', + 'OccupancyCountingPredictionResult', + 'PersonalProtectiveEquipmentDetectionOutput', + 'StreamAnnotation', + 'StreamAnnotations', + 'VideoActionRecognitionPredictionResult', + 'VideoClassificationPredictionResult', + 'VideoObjectTrackingPredictionResult', + 'StreamAnnotationType', + 'Cluster', + 'GcsSource', + 'OperationMetadata', + 'AnalysisDefinition', + 'AnalyzerDefinition', + 'AttributeValue', + 'Analysis', + 'CreateAnalysisRequest', + 'DeleteAnalysisRequest', + 'GetAnalysisRequest', + 'ListAnalysesRequest', + 'ListAnalysesResponse', + 'UpdateAnalysisRequest', + 'AddApplicationStreamInputRequest', + 'AddApplicationStreamInputResponse', + 'AIEnabledDevicesInputConfig', + 'Application', + 'ApplicationConfigs', + 'ApplicationInstance', + 'ApplicationNodeAnnotation', + 'ApplicationStreamInput', + 'AutoscalingMetricSpec', + 'BigQueryConfig', + 'CreateApplicationInstancesRequest', + 'CreateApplicationInstancesResponse', + 'CreateApplicationRequest', + 'CreateDraftRequest', + 'CreateProcessorRequest', + 'CustomProcessorSourceInfo', + 'DedicatedResources', + 'DeleteApplicationInstancesRequest', + 'DeleteApplicationInstancesResponse', + 'DeleteApplicationRequest', + 'DeleteDraftRequest', + 'DeleteProcessorRequest', + 'DeployApplicationRequest', + 'DeployApplicationResponse', + 'Draft', + 'GeneralObjectDetectionConfig', + 'GetApplicationRequest', + 'GetDraftRequest', + 'GetInstanceRequest', + 'GetProcessorRequest', + 'Instance', + 'ListApplicationsRequest', + 'ListApplicationsResponse', + 'ListDraftsRequest', + 'ListDraftsResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListPrebuiltProcessorsRequest', + 'ListPrebuiltProcessorsResponse', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'MachineSpec', + 'MediaWarehouseConfig', + 'Node', + 'OccupancyCountConfig', + 'PersonalProtectiveEquipmentDetectionConfig', + 'PersonBlurConfig', + 'PersonVehicleDetectionConfig', + 'Processor', + 'ProcessorConfig', + 'ProcessorIOSpec', + 'RemoveApplicationStreamInputRequest', + 'RemoveApplicationStreamInputResponse', + 'ResourceAnnotations', + 'StreamWithAnnotation', + 'UndeployApplicationRequest', + 'UndeployApplicationResponse', + 'UpdateApplicationInstancesRequest', + 'UpdateApplicationInstancesResponse', + 'UpdateApplicationRequest', + 'UpdateApplicationStreamInputRequest', + 'UpdateApplicationStreamInputResponse', + 'UpdateDraftRequest', + 'UpdateProcessorRequest', + 'VertexAutoMLVideoConfig', + 'VertexAutoMLVisionConfig', + 'VertexCustomConfig', + 'VideoStreamInputConfig', + 'AcceleratorType', + 'ModelType', + 'GstreamerBufferDescriptor', + 'Packet', + 'PacketHeader', + 'PacketType', + 'RawImageDescriptor', + 'SeriesMetadata', + 'ServerMetadata', + 'AcquireLeaseRequest', + 'CommitRequest', + 'ControlledMode', + 'EagerMode', + 'EventUpdate', + 'Lease', + 'ReceiveEventsControlResponse', + 'ReceiveEventsRequest', + 'ReceiveEventsResponse', + 'ReceivePacketsControlResponse', + 'ReceivePacketsRequest', + 'ReceivePacketsResponse', + 'ReleaseLeaseRequest', + 'ReleaseLeaseResponse', + 'RenewLeaseRequest', + 'RequestMetadata', + 'SendPacketsRequest', + 'SendPacketsResponse', + 'LeaseType', + 'Channel', + 'Event', + 'Series', + 'Stream', + 'CreateClusterRequest', + 'CreateEventRequest', + 'CreateSeriesRequest', + 'CreateStreamRequest', + 'DeleteClusterRequest', + 'DeleteEventRequest', + 'DeleteSeriesRequest', + 'DeleteStreamRequest', + 'GenerateStreamHlsTokenRequest', + 'GenerateStreamHlsTokenResponse', + 'GetClusterRequest', + 'GetEventRequest', + 'GetSeriesRequest', + 'GetStreamRequest', + 'GetStreamThumbnailResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListEventsRequest', + 'ListEventsResponse', + 'ListSeriesRequest', + 'ListSeriesResponse', + 'ListStreamsRequest', + 'ListStreamsResponse', + 'MaterializeChannelRequest', + 'UpdateClusterRequest', + 'UpdateEventRequest', + 'UpdateSeriesRequest', + 'UpdateStreamRequest', + 'Annotation', + 'AnnotationMatchingResult', + 'AnnotationValue', + 'Asset', + 'BoolValue', + 'CircleArea', + 'ClipAssetRequest', + 'ClipAssetResponse', + 'Corpus', + 'CreateAnnotationRequest', + 'CreateAssetRequest', + 'CreateCorpusMetadata', + 'CreateCorpusRequest', + 'CreateDataSchemaRequest', + 'CreateSearchConfigRequest', + 'Criteria', + 'DataSchema', + 'DataSchemaDetails', + 'DateTimeRange', + 'DateTimeRangeArray', + 'DeleteAnnotationRequest', + 'DeleteAssetMetadata', + 'DeleteAssetRequest', + 'DeleteCorpusRequest', + 'DeleteDataSchemaRequest', + 'DeleteSearchConfigRequest', + 'FacetBucket', + 'FacetGroup', + 'FacetProperty', + 'FacetValue', + 'FloatRange', + 'FloatRangeArray', + 'GenerateHlsUriRequest', + 'GenerateHlsUriResponse', + 'GeoCoordinate', + 'GeoLocationArray', + 'GetAnnotationRequest', + 'GetAssetRequest', + 'GetCorpusRequest', + 'GetDataSchemaRequest', + 'GetSearchConfigRequest', + 'IngestAssetRequest', + 'IngestAssetResponse', + 'IntRange', + 'IntRangeArray', + 'ListAnnotationsRequest', + 'ListAnnotationsResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListCorporaRequest', + 'ListCorporaResponse', + 'ListDataSchemasRequest', + 'ListDataSchemasResponse', + 'ListSearchConfigsRequest', + 'ListSearchConfigsResponse', + 'Partition', + 'SearchAssetsRequest', + 'SearchAssetsResponse', + 'SearchConfig', + 'SearchCriteriaProperty', + 'SearchResultItem', + 'StringArray', + 'UpdateAnnotationRequest', + 'UpdateAssetRequest', + 'UpdateCorpusRequest', + 'UpdateDataSchemaRequest', + 'UpdateSearchConfigRequest', + 'UserSpecifiedAnnotation', + 'FacetBucketType', +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/annotations.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/annotations.py new file mode 100644 index 000000000000..47edc7f83a58 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/annotations.py @@ -0,0 +1,1442 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'StreamAnnotationType', + 'PersonalProtectiveEquipmentDetectionOutput', + 'ObjectDetectionPredictionResult', + 'ImageObjectDetectionPredictionResult', + 'ClassificationPredictionResult', + 'ImageSegmentationPredictionResult', + 'VideoActionRecognitionPredictionResult', + 'VideoObjectTrackingPredictionResult', + 'VideoClassificationPredictionResult', + 'OccupancyCountingPredictionResult', + 'StreamAnnotation', + 'StreamAnnotations', + 'NormalizedPolygon', + 'NormalizedPolyline', + 'NormalizedVertex', + 'AppPlatformMetadata', + 'AppPlatformCloudFunctionRequest', + 'AppPlatformCloudFunctionResponse', + 'AppPlatformEventBody', + }, +) + + +class StreamAnnotationType(proto.Enum): + r"""Enum describing all possible types of a stream annotation. + + Values: + STREAM_ANNOTATION_TYPE_UNSPECIFIED (0): + Type UNSPECIFIED. + STREAM_ANNOTATION_TYPE_ACTIVE_ZONE (1): + active_zone annotation defines a polygon on top of the + content from an image/video based stream, following + processing will only focus on the content inside the active + zone. + STREAM_ANNOTATION_TYPE_CROSSING_LINE (2): + crossing_line annotation defines a polyline on top of the + content from an image/video based Vision AI stream, events + happening across the line will be captured. For example, the + counts of people who goes acroos the line in Occupancy + Analytic Processor. + """ + STREAM_ANNOTATION_TYPE_UNSPECIFIED = 0 + STREAM_ANNOTATION_TYPE_ACTIVE_ZONE = 1 + STREAM_ANNOTATION_TYPE_CROSSING_LINE = 2 + + +class PersonalProtectiveEquipmentDetectionOutput(proto.Message): + r"""Output format for Personal Protective Equipment Detection + Operator. + + Attributes: + current_time (google.protobuf.timestamp_pb2.Timestamp): + Current timestamp. + detected_persons (MutableSequence[google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionOutput.DetectedPerson]): + A list of DetectedPersons. + """ + + class PersonEntity(proto.Message): + r"""The entity info for annotations from person detection + prediction result. + + Attributes: + person_entity_id (int): + Entity id. + """ + + person_entity_id: int = proto.Field( + proto.INT64, + number=1, + ) + + class PPEEntity(proto.Message): + r"""The entity info for annotations from PPE detection prediction + result. + + Attributes: + ppe_label_id (int): + Label id. + ppe_label_string (str): + Human readable string of the label (Examples: + helmet, glove, mask). + ppe_supercategory_label_string (str): + Human readable string of the super category label (Examples: + head_cover, hands_cover, face_cover). + ppe_entity_id (int): + Entity id. + """ + + ppe_label_id: int = proto.Field( + proto.INT64, + number=1, + ) + ppe_label_string: str = proto.Field( + proto.STRING, + number=2, + ) + ppe_supercategory_label_string: str = proto.Field( + proto.STRING, + number=3, + ) + ppe_entity_id: int = proto.Field( + proto.INT64, + number=4, + ) + + class NormalizedBoundingBox(proto.Message): + r"""Bounding Box in the normalized coordinates. + + Attributes: + xmin (float): + Min in x coordinate. + ymin (float): + Min in y coordinate. + width (float): + Width of the bounding box. + height (float): + Height of the bounding box. + """ + + xmin: float = proto.Field( + proto.FLOAT, + number=1, + ) + ymin: float = proto.Field( + proto.FLOAT, + number=2, + ) + width: float = proto.Field( + proto.FLOAT, + number=3, + ) + height: float = proto.Field( + proto.FLOAT, + number=4, + ) + + class PersonIdentifiedBox(proto.Message): + r"""PersonIdentified box contains the location and the entity + info of the person. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + confidence_score (float): + Confidence score associated with this box. + person_entity (google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionOutput.PersonEntity): + Person entity info. + """ + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox', + ) + confidence_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + person_entity: 'PersonalProtectiveEquipmentDetectionOutput.PersonEntity' = proto.Field( + proto.MESSAGE, + number=4, + message='PersonalProtectiveEquipmentDetectionOutput.PersonEntity', + ) + + class PPEIdentifiedBox(proto.Message): + r"""PPEIdentified box contains the location and the entity info + of the PPE. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + confidence_score (float): + Confidence score associated with this box. + ppe_entity (google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionOutput.PPEEntity): + PPE entity info. + """ + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='PersonalProtectiveEquipmentDetectionOutput.NormalizedBoundingBox', + ) + confidence_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + ppe_entity: 'PersonalProtectiveEquipmentDetectionOutput.PPEEntity' = proto.Field( + proto.MESSAGE, + number=4, + message='PersonalProtectiveEquipmentDetectionOutput.PPEEntity', + ) + + class DetectedPerson(proto.Message): + r"""Detected Person contains the detected person and their + associated ppes and their protecting information. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + person_id (int): + The id of detected person. + detected_person_identified_box (google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionOutput.PersonIdentifiedBox): + The info of detected person identified box. + detected_ppe_identified_boxes (MutableSequence[google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionOutput.PPEIdentifiedBox]): + The info of detected person associated ppe + identified boxes. + face_coverage_score (float): + Coverage score for each body part. + Coverage score for face. + + This field is a member of `oneof`_ ``_face_coverage_score``. + eyes_coverage_score (float): + Coverage score for eyes. + + This field is a member of `oneof`_ ``_eyes_coverage_score``. + head_coverage_score (float): + Coverage score for head. + + This field is a member of `oneof`_ ``_head_coverage_score``. + hands_coverage_score (float): + Coverage score for hands. + + This field is a member of `oneof`_ ``_hands_coverage_score``. + body_coverage_score (float): + Coverage score for body. + + This field is a member of `oneof`_ ``_body_coverage_score``. + feet_coverage_score (float): + Coverage score for feet. + + This field is a member of `oneof`_ ``_feet_coverage_score``. + """ + + person_id: int = proto.Field( + proto.INT64, + number=1, + ) + detected_person_identified_box: 'PersonalProtectiveEquipmentDetectionOutput.PersonIdentifiedBox' = proto.Field( + proto.MESSAGE, + number=2, + message='PersonalProtectiveEquipmentDetectionOutput.PersonIdentifiedBox', + ) + detected_ppe_identified_boxes: MutableSequence['PersonalProtectiveEquipmentDetectionOutput.PPEIdentifiedBox'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='PersonalProtectiveEquipmentDetectionOutput.PPEIdentifiedBox', + ) + face_coverage_score: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + eyes_coverage_score: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + head_coverage_score: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + hands_coverage_score: float = proto.Field( + proto.FLOAT, + number=7, + optional=True, + ) + body_coverage_score: float = proto.Field( + proto.FLOAT, + number=8, + optional=True, + ) + feet_coverage_score: float = proto.Field( + proto.FLOAT, + number=9, + optional=True, + ) + + current_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + detected_persons: MutableSequence[DetectedPerson] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=DetectedPerson, + ) + + +class ObjectDetectionPredictionResult(proto.Message): + r"""Prediction output format for Generic Object Detection. + + Attributes: + current_time (google.protobuf.timestamp_pb2.Timestamp): + Current timestamp. + identified_boxes (MutableSequence[google.cloud.visionai_v1alpha1.types.ObjectDetectionPredictionResult.IdentifiedBox]): + A list of identified boxes. + """ + + class Entity(proto.Message): + r"""The entity info for annotations from object detection + prediction result. + + Attributes: + label_id (int): + Label id. + label_string (str): + Human readable string of the label. + """ + + label_id: int = proto.Field( + proto.INT64, + number=1, + ) + label_string: str = proto.Field( + proto.STRING, + number=2, + ) + + class IdentifiedBox(proto.Message): + r"""Identified box contains location and the entity of the + object. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1alpha1.types.ObjectDetectionPredictionResult.IdentifiedBox.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + confidence_score (float): + Confidence score associated with this box. + entity (google.cloud.visionai_v1alpha1.types.ObjectDetectionPredictionResult.Entity): + Entity of this box. + """ + + class NormalizedBoundingBox(proto.Message): + r"""Bounding Box in the normalized coordinates. + + Attributes: + xmin (float): + Min in x coordinate. + ymin (float): + Min in y coordinate. + width (float): + Width of the bounding box. + height (float): + Height of the bounding box. + """ + + xmin: float = proto.Field( + proto.FLOAT, + number=1, + ) + ymin: float = proto.Field( + proto.FLOAT, + number=2, + ) + width: float = proto.Field( + proto.FLOAT, + number=3, + ) + height: float = proto.Field( + proto.FLOAT, + number=4, + ) + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'ObjectDetectionPredictionResult.IdentifiedBox.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='ObjectDetectionPredictionResult.IdentifiedBox.NormalizedBoundingBox', + ) + confidence_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + entity: 'ObjectDetectionPredictionResult.Entity' = proto.Field( + proto.MESSAGE, + number=4, + message='ObjectDetectionPredictionResult.Entity', + ) + + current_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + identified_boxes: MutableSequence[IdentifiedBox] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=IdentifiedBox, + ) + + +class ImageObjectDetectionPredictionResult(proto.Message): + r"""Prediction output format for Image Object Detection. + + Attributes: + ids (MutableSequence[int]): + The resource IDs of the AnnotationSpecs that + had been identified, ordered by the confidence + score descendingly. It is the id segment instead + of full resource name. + display_names (MutableSequence[str]): + The display names of the AnnotationSpecs that + had been identified, order matches the IDs. + confidences (MutableSequence[float]): + The Model's confidences in correctness of the + predicted IDs, higher value means higher + confidence. Order matches the Ids. + bboxes (MutableSequence[google.protobuf.struct_pb2.ListValue]): + Bounding boxes, i.e. the rectangles over the image, that + pinpoint the found AnnotationSpecs. Given in order that + matches the IDs. Each bounding box is an array of 4 numbers + ``xMin``, ``xMax``, ``yMin``, and ``yMax``, which represent + the extremal coordinates of the box. They are relative to + the image size, and the point 0,0 is in the top left of the + image. + """ + + ids: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=1, + ) + display_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + confidences: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=3, + ) + bboxes: MutableSequence[struct_pb2.ListValue] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=struct_pb2.ListValue, + ) + + +class ClassificationPredictionResult(proto.Message): + r"""Prediction output format for Image and Text Classification. + + Attributes: + ids (MutableSequence[int]): + The resource IDs of the AnnotationSpecs that + had been identified. + display_names (MutableSequence[str]): + The display names of the AnnotationSpecs that + had been identified, order matches the IDs. + confidences (MutableSequence[float]): + The Model's confidences in correctness of the + predicted IDs, higher value means higher + confidence. Order matches the Ids. + """ + + ids: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=1, + ) + display_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + confidences: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=3, + ) + + +class ImageSegmentationPredictionResult(proto.Message): + r"""Prediction output format for Image Segmentation. + + Attributes: + category_mask (str): + A PNG image where each pixel in the mask + represents the category in which the pixel in + the original image was predicted to belong to. + The size of this image will be the same as the + original image. The mapping between the + AnntoationSpec and the color can be found in + model's metadata. The model will choose the most + likely category and if none of the categories + reach the confidence threshold, the pixel will + be marked as background. + confidence_mask (str): + A one channel image which is encoded as an + 8bit lossless PNG. The size of the image will be + the same as the original image. For a specific + pixel, darker color means less confidence in + correctness of the cateogry in the categoryMask + for the corresponding pixel. Black means no + confidence and white means complete confidence. + """ + + category_mask: str = proto.Field( + proto.STRING, + number=1, + ) + confidence_mask: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VideoActionRecognitionPredictionResult(proto.Message): + r"""Prediction output format for Video Action Recognition. + + Attributes: + segment_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning, inclusive, of the video's time + segment in which the actions have been + identified. + segment_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end, inclusive, of the video's time + segment in which the actions have been + identified. Particularly, if the end is the same + as the start, it means the identification + happens on a specific video frame. + actions (MutableSequence[google.cloud.visionai_v1alpha1.types.VideoActionRecognitionPredictionResult.IdentifiedAction]): + All of the actions identified in the time + range. + """ + + class IdentifiedAction(proto.Message): + r"""Each IdentifiedAction is one particular identification of an action + specified with the AnnotationSpec id, display_name and the + associated confidence score. + + Attributes: + id (str): + The resource ID of the AnnotationSpec that + had been identified. + display_name (str): + The display name of the AnnotationSpec that + had been identified. + confidence (float): + The Model's confidence in correction of this + identification, higher value means higher + confidence. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=3, + ) + + segment_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + segment_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + actions: MutableSequence[IdentifiedAction] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=IdentifiedAction, + ) + + +class VideoObjectTrackingPredictionResult(proto.Message): + r"""Prediction output format for Video Object Tracking. + + Attributes: + segment_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning, inclusive, of the video's time + segment in which the current identifications + happens. + segment_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end, inclusive, of the video's time + segment in which the current identifications + happen. Particularly, if the end is the same as + the start, it means the identifications happen + on a specific video frame. + objects (MutableSequence[google.cloud.visionai_v1alpha1.types.VideoObjectTrackingPredictionResult.DetectedObject]): + All of the objects detected in the specified + time range. + """ + + class BoundingBox(proto.Message): + r"""Boundingbox for detected object. I.e. the rectangle over the + video frame pinpointing the found AnnotationSpec. The + coordinates are relative to the frame size, and the point 0,0 is + in the top left of the frame. + + Attributes: + x_min (float): + The leftmost coordinate of the bounding box. + x_max (float): + The rightmost coordinate of the bounding box. + y_min (float): + The topmost coordinate of the bounding box. + y_max (float): + The bottommost coordinate of the bounding + box. + """ + + x_min: float = proto.Field( + proto.FLOAT, + number=1, + ) + x_max: float = proto.Field( + proto.FLOAT, + number=2, + ) + y_min: float = proto.Field( + proto.FLOAT, + number=3, + ) + y_max: float = proto.Field( + proto.FLOAT, + number=4, + ) + + class DetectedObject(proto.Message): + r"""Each DetectedObject is one particular identification of an object + specified with the AnnotationSpec id and display_name, the bounding + box, the associated confidence score and the corresponding track_id. + + Attributes: + id (str): + The resource ID of the AnnotationSpec that + had been identified. + display_name (str): + The display name of the AnnotationSpec that + had been identified. + bounding_box (google.cloud.visionai_v1alpha1.types.VideoObjectTrackingPredictionResult.BoundingBox): + Boundingbox. + confidence (float): + The Model's confidence in correction of this + identification, higher value means higher + confidence. + track_id (int): + The same object may be identified on muitiple frames which + are typical adjacent. The set of frames where a particular + object has been detected form a track. This track_id can be + used to trace down all frames for an detected object. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + bounding_box: 'VideoObjectTrackingPredictionResult.BoundingBox' = proto.Field( + proto.MESSAGE, + number=3, + message='VideoObjectTrackingPredictionResult.BoundingBox', + ) + confidence: float = proto.Field( + proto.FLOAT, + number=4, + ) + track_id: int = proto.Field( + proto.INT64, + number=5, + ) + + segment_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + segment_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + objects: MutableSequence[DetectedObject] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=DetectedObject, + ) + + +class VideoClassificationPredictionResult(proto.Message): + r"""Prediction output format for Video Classification. + + Attributes: + segment_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning, inclusive, of the video's time + segment in which the classifications have been + identified. + segment_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end, inclusive, of the video's time + segment in which the classifications have been + identified. Particularly, if the end is the same + as the start, it means the identification + happens on a specific video frame. + classifications (MutableSequence[google.cloud.visionai_v1alpha1.types.VideoClassificationPredictionResult.IdentifiedClassification]): + All of the classifications identified in the + time range. + """ + + class IdentifiedClassification(proto.Message): + r"""Each IdentifiedClassification is one particular identification of an + classification specified with the AnnotationSpec id and + display_name, and the associated confidence score. + + Attributes: + id (str): + The resource ID of the AnnotationSpec that + had been identified. + display_name (str): + The display name of the AnnotationSpec that + had been identified. + confidence (float): + The Model's confidence in correction of this + identification, higher value means higher + confidence. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=3, + ) + + segment_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + segment_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + classifications: MutableSequence[IdentifiedClassification] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=IdentifiedClassification, + ) + + +class OccupancyCountingPredictionResult(proto.Message): + r"""The prediction result proto for occupancy counting. + + Attributes: + current_time (google.protobuf.timestamp_pb2.Timestamp): + Current timestamp. + identified_boxes (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.IdentifiedBox]): + A list of identified boxes. + stats (google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats): + Detection statistics. + track_info (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.TrackInfo]): + Track related information. All the tracks + that are live at this timestamp. It only exists + if tracking is enabled. + dwell_time_info (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.DwellTimeInfo]): + Dwell time related information. All the + tracks that are live in a given zone with a + start and end dwell time timestamp + """ + + class Entity(proto.Message): + r"""The entity info for annotations from occupancy counting + operator. + + Attributes: + label_id (int): + Label id. + label_string (str): + Human readable string of the label. + """ + + label_id: int = proto.Field( + proto.INT64, + number=1, + ) + label_string: str = proto.Field( + proto.STRING, + number=2, + ) + + class IdentifiedBox(proto.Message): + r"""Identified box contains location and the entity of the + object. + + Attributes: + box_id (int): + An unique id for this box. + normalized_bounding_box (google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.IdentifiedBox.NormalizedBoundingBox): + Bounding Box in the normalized coordinates. + score (float): + Confidence score associated with this box. + entity (google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Entity): + Entity of this box. + track_id (int): + An unique id to identify a track. It should + be consistent across frames. It only exists if + tracking is enabled. + """ + + class NormalizedBoundingBox(proto.Message): + r"""Bounding Box in the normalized coordinates. + + Attributes: + xmin (float): + Min in x coordinate. + ymin (float): + Min in y coordinate. + width (float): + Width of the bounding box. + height (float): + Height of the bounding box. + """ + + xmin: float = proto.Field( + proto.FLOAT, + number=1, + ) + ymin: float = proto.Field( + proto.FLOAT, + number=2, + ) + width: float = proto.Field( + proto.FLOAT, + number=3, + ) + height: float = proto.Field( + proto.FLOAT, + number=4, + ) + + box_id: int = proto.Field( + proto.INT64, + number=1, + ) + normalized_bounding_box: 'OccupancyCountingPredictionResult.IdentifiedBox.NormalizedBoundingBox' = proto.Field( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.IdentifiedBox.NormalizedBoundingBox', + ) + score: float = proto.Field( + proto.FLOAT, + number=3, + ) + entity: 'OccupancyCountingPredictionResult.Entity' = proto.Field( + proto.MESSAGE, + number=4, + message='OccupancyCountingPredictionResult.Entity', + ) + track_id: int = proto.Field( + proto.INT64, + number=5, + ) + + class Stats(proto.Message): + r"""The statistics info for annotations from occupancy counting + operator. + + Attributes: + full_frame_count (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + Counts of the full frame. + crossing_line_counts (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.CrossingLineCount]): + Crossing line counts. + active_zone_counts (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.ActiveZoneCount]): + Active zone counts. + """ + + class ObjectCount(proto.Message): + r"""The object info and instant count for annotations from + occupancy counting operator. + + Attributes: + entity (google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Entity): + Entity of this object. + count (int): + Count of the object. + """ + + entity: 'OccupancyCountingPredictionResult.Entity' = proto.Field( + proto.MESSAGE, + number=1, + message='OccupancyCountingPredictionResult.Entity', + ) + count: int = proto.Field( + proto.INT32, + number=2, + ) + + class AccumulatedObjectCount(proto.Message): + r"""The object info and accumulated count for annotations from + occupancy counting operator. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start time of the accumulated count. + object_count (google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.ObjectCount): + The object count for the accumulated count. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + object_count: 'OccupancyCountingPredictionResult.Stats.ObjectCount' = proto.Field( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + + class CrossingLineCount(proto.Message): + r"""Message for Crossing line count. + + Attributes: + annotation (google.cloud.visionai_v1alpha1.types.StreamAnnotation): + Line annotation from the user. + positive_direction_counts (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + The direction that follows the right hand + rule. + negative_direction_counts (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + The direction that is opposite to the right + hand rule. + accumulated_positive_direction_counts (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount]): + The accumulated positive count. + accumulated_negative_direction_counts (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount]): + The accumulated negative count. + """ + + annotation: 'StreamAnnotation' = proto.Field( + proto.MESSAGE, + number=1, + message='StreamAnnotation', + ) + positive_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + negative_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + accumulated_positive_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount', + ) + accumulated_negative_direction_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='OccupancyCountingPredictionResult.Stats.AccumulatedObjectCount', + ) + + class ActiveZoneCount(proto.Message): + r"""Message for the active zone count. + + Attributes: + annotation (google.cloud.visionai_v1alpha1.types.StreamAnnotation): + Active zone annotation from the user. + counts (MutableSequence[google.cloud.visionai_v1alpha1.types.OccupancyCountingPredictionResult.Stats.ObjectCount]): + Counts in the zone. + """ + + annotation: 'StreamAnnotation' = proto.Field( + proto.MESSAGE, + number=1, + message='StreamAnnotation', + ) + counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + + full_frame_count: MutableSequence['OccupancyCountingPredictionResult.Stats.ObjectCount'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OccupancyCountingPredictionResult.Stats.ObjectCount', + ) + crossing_line_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.CrossingLineCount'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OccupancyCountingPredictionResult.Stats.CrossingLineCount', + ) + active_zone_counts: MutableSequence['OccupancyCountingPredictionResult.Stats.ActiveZoneCount'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='OccupancyCountingPredictionResult.Stats.ActiveZoneCount', + ) + + class TrackInfo(proto.Message): + r"""The track info for annotations from occupancy counting + operator. + + Attributes: + track_id (str): + An unique id to identify a track. It should + be consistent across frames. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start timestamp of this track. + """ + + track_id: str = proto.Field( + proto.STRING, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class DwellTimeInfo(proto.Message): + r"""The dwell time info for annotations from occupancy counting + operator. + + Attributes: + track_id (str): + An unique id to identify a track. It should + be consistent across frames. + zone_id (str): + The unique id for the zone in which the + object is dwelling/waiting. + dwell_start_time (google.protobuf.timestamp_pb2.Timestamp): + The beginning time when a dwelling object has + been identified in a zone. + dwell_end_time (google.protobuf.timestamp_pb2.Timestamp): + The end time when a dwelling object has + exited in a zone. + """ + + track_id: str = proto.Field( + proto.STRING, + number=1, + ) + zone_id: str = proto.Field( + proto.STRING, + number=2, + ) + dwell_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + dwell_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + current_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + identified_boxes: MutableSequence[IdentifiedBox] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=IdentifiedBox, + ) + stats: Stats = proto.Field( + proto.MESSAGE, + number=3, + message=Stats, + ) + track_info: MutableSequence[TrackInfo] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=TrackInfo, + ) + dwell_time_info: MutableSequence[DwellTimeInfo] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=DwellTimeInfo, + ) + + +class StreamAnnotation(proto.Message): + r"""message about annotations about Vision AI stream resource. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + active_zone (google.cloud.visionai_v1alpha1.types.NormalizedPolygon): + Annotation for type ACTIVE_ZONE + + This field is a member of `oneof`_ ``annotation_payload``. + crossing_line (google.cloud.visionai_v1alpha1.types.NormalizedPolyline): + Annotation for type CROSSING_LINE + + This field is a member of `oneof`_ ``annotation_payload``. + id (str): + ID of the annotation. It must be unique when + used in the certain context. For example, all + the annotations to one input streams of a Vision + AI application. + display_name (str): + User-friendly name for the annotation. + source_stream (str): + The Vision AI stream resource name. + type_ (google.cloud.visionai_v1alpha1.types.StreamAnnotationType): + The actual type of Annotation. + """ + + active_zone: 'NormalizedPolygon' = proto.Field( + proto.MESSAGE, + number=5, + oneof='annotation_payload', + message='NormalizedPolygon', + ) + crossing_line: 'NormalizedPolyline' = proto.Field( + proto.MESSAGE, + number=6, + oneof='annotation_payload', + message='NormalizedPolyline', + ) + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + source_stream: str = proto.Field( + proto.STRING, + number=3, + ) + type_: 'StreamAnnotationType' = proto.Field( + proto.ENUM, + number=4, + enum='StreamAnnotationType', + ) + + +class StreamAnnotations(proto.Message): + r"""A wrapper of repeated StreamAnnotation. + + Attributes: + stream_annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamAnnotation]): + Multiple annotations. + """ + + stream_annotations: MutableSequence['StreamAnnotation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='StreamAnnotation', + ) + + +class NormalizedPolygon(proto.Message): + r"""Normalized Polygon. + + Attributes: + normalized_vertices (MutableSequence[google.cloud.visionai_v1alpha1.types.NormalizedVertex]): + The bounding polygon normalized vertices. Top left corner of + the image will be [0, 0]. + """ + + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class NormalizedPolyline(proto.Message): + r"""Normalized Pplyline, which represents a curve consisting of + connected straight-line segments. + + Attributes: + normalized_vertices (MutableSequence[google.cloud.visionai_v1alpha1.types.NormalizedVertex]): + A sequence of vertices connected by straight + lines. + """ + + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x: float = proto.Field( + proto.FLOAT, + number=1, + ) + y: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class AppPlatformMetadata(proto.Message): + r"""Message of essential metadata of App Platform. + This message is usually attached to a certain processor output + annotation for customer to identify the source of the data. + + Attributes: + application (str): + The application resource name. + instance_id (str): + The instance resource id. Instance is the + nested resource of application under collection + 'instances'. + node (str): + The node name of the application graph. + processor (str): + The referred processor resource name of the + application node. + """ + + application: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + node: str = proto.Field( + proto.STRING, + number=3, + ) + processor: str = proto.Field( + proto.STRING, + number=4, + ) + + +class AppPlatformCloudFunctionRequest(proto.Message): + r"""For any cloud function based customer processing logic, + customer's cloud function is expected to receive + AppPlatformCloudFunctionRequest as request and send back + AppPlatformCloudFunctionResponse as response. Message of request + from AppPlatform to Cloud Function. + + Attributes: + app_platform_metadata (google.cloud.visionai_v1alpha1.types.AppPlatformMetadata): + The metadata of the AppPlatform for customer + to identify the source of the payload. + annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.AppPlatformCloudFunctionRequest.StructedInputAnnotation]): + The actual annotations to be processed by the + customized Cloud Function. + """ + + class StructedInputAnnotation(proto.Message): + r"""A general annotation message that uses struct format to + represent different concrete annotation protobufs. + + Attributes: + ingestion_time_micros (int): + The ingestion time of the current annotation. + annotation (google.protobuf.struct_pb2.Struct): + The struct format of the actual annotation. + """ + + ingestion_time_micros: int = proto.Field( + proto.INT64, + number=1, + ) + annotation: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + + app_platform_metadata: 'AppPlatformMetadata' = proto.Field( + proto.MESSAGE, + number=1, + message='AppPlatformMetadata', + ) + annotations: MutableSequence[StructedInputAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=StructedInputAnnotation, + ) + + +class AppPlatformCloudFunctionResponse(proto.Message): + r"""Message of the response from customer's Cloud Function to + AppPlatform. + + Attributes: + annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.AppPlatformCloudFunctionResponse.StructedOutputAnnotation]): + The modified annotations that is returned + back to AppPlatform. If the annotations fields + are empty, then those annotations will be + dropped by AppPlatform. + annotation_passthrough (bool): + If set to true, AppPlatform will use original + annotations instead of dropping them, even if it + is empty in the annotations filed. + events (MutableSequence[google.cloud.visionai_v1alpha1.types.AppPlatformEventBody]): + The event notifications that is returned back + to AppPlatform. Typically it will then be + configured to be consumed/forwared to a operator + that handles events, such as Pub/Sub operator. + """ + + class StructedOutputAnnotation(proto.Message): + r"""A general annotation message that uses struct format to + represent different concrete annotation protobufs. + + Attributes: + annotation (google.protobuf.struct_pb2.Struct): + The struct format of the actual annotation. + """ + + annotation: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + annotations: MutableSequence[StructedOutputAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=StructedOutputAnnotation, + ) + annotation_passthrough: bool = proto.Field( + proto.BOOL, + number=3, + ) + events: MutableSequence['AppPlatformEventBody'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AppPlatformEventBody', + ) + + +class AppPlatformEventBody(proto.Message): + r"""Message of content of appPlatform event + + Attributes: + event_message (str): + Human readable string of the event like + "There are more than 6 people in the scene". or + "Shelf is empty!". + payload (google.protobuf.struct_pb2.Struct): + For the case of Pub/Sub, it will be stored in + the message attributes. ​​pubsub.proto + event_id (str): + User defined Event Id, used to classify event, within a + delivery interval, events from the same application instance + with the same id will be de-duplicated & only first one will + be sent out. Empty event_id will be treated as "". + """ + + event_message: str = proto.Field( + proto.STRING, + number=1, + ) + payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + event_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/common.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/common.py new file mode 100644 index 000000000000..5450ab1d89e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/common.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'Cluster', + 'OperationMetadata', + 'GcsSource', + }, +) + + +class Cluster(proto.Message): + r"""Message describing the Cluster object. + + Attributes: + name (str): + Output only. Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + dataplane_service_endpoint (str): + Output only. The DNS name of the data plane + service + state (google.cloud.visionai_v1alpha1.types.Cluster.State): + Output only. The current state of the + cluster. + psc_target (str): + Output only. The private service connection + service target name. + """ + class State(proto.Enum): + r"""The current state of the cluster. + + Values: + STATE_UNSPECIFIED (0): + Not set. + PROVISIONING (1): + The PROVISIONING state indicates the cluster + is being created. + RUNNING (2): + The RUNNING state indicates the cluster has + been created and is fully usable. + STOPPING (3): + The STOPPING state indicates the cluster is + being deleted. + ERROR (4): + The ERROR state indicates the cluster is + unusable. It will be automatically deleted. + """ + STATE_UNSPECIFIED = 0 + PROVISIONING = 1 + RUNNING = 2 + STOPPING = 3 + ERROR = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + dataplane_service_endpoint: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + psc_target: str = proto.Field( + proto.STRING, + number=8, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location for the input content. + + Attributes: + uris (MutableSequence[str]): + Required. References to a Google Cloud + Storage paths. + """ + + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva.py new file mode 100644 index 000000000000..820b8a61adaa --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'AttributeValue', + 'AnalyzerDefinition', + 'AnalysisDefinition', + }, +) + + +class AttributeValue(proto.Message): + r"""Represents an actual value of an operator attribute. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + i (int): + int. + + This field is a member of `oneof`_ ``value``. + f (float): + float. + + This field is a member of `oneof`_ ``value``. + b (bool): + bool. + + This field is a member of `oneof`_ ``value``. + s (bytes): + string. + + This field is a member of `oneof`_ ``value``. + """ + + i: int = proto.Field( + proto.INT64, + number=1, + oneof='value', + ) + f: float = proto.Field( + proto.FLOAT, + number=2, + oneof='value', + ) + b: bool = proto.Field( + proto.BOOL, + number=3, + oneof='value', + ) + s: bytes = proto.Field( + proto.BYTES, + number=4, + oneof='value', + ) + + +class AnalyzerDefinition(proto.Message): + r"""Defines an Analyzer. + + An analyzer processes data from its input streams using the + logic defined in the Operator that it represents. Of course, it + produces data for the output streams declared in the Operator. + + Attributes: + analyzer (str): + The name of this analyzer. + + Tentatively [a-z][a-z0-9]*(_[a-z0-9]+)*. + operator (str): + The name of the operator that this analyzer + runs. + Must match the name of a supported operator. + inputs (MutableSequence[google.cloud.visionai_v1alpha1.types.AnalyzerDefinition.StreamInput]): + Input streams. + attrs (MutableMapping[str, google.cloud.visionai_v1alpha1.types.AttributeValue]): + The attribute values that this analyzer + applies to the operator. + Supply a mapping between the attribute names and + the actual value you wish to apply. If an + attribute name is omitted, then it will take a + preconfigured default value. + debug_options (google.cloud.visionai_v1alpha1.types.AnalyzerDefinition.DebugOptions): + Debug options. + """ + + class StreamInput(proto.Message): + r"""The inputs to this analyzer. + + We accept input name references of the following form: : + + Example: + + Suppose you had an operator named "SomeOp" that has 2 output + arguments, the first of which is named "foo" and the second of which + is named "bar", and an operator named "MyOp" that accepts 2 inputs. + + Also suppose that there is an analyzer named "some-analyzer" that is + running "SomeOp" and another analyzer named "my-analyzer" running + "MyOp". + + To indicate that "my-analyzer" is to consume "some-analyzer"'s "foo" + output as its first input and "some-analyzer"'s "bar" output as its + second input, you can set this field to the following: input = + ["some-analyzer:foo", "some-analyzer:bar"] + + Attributes: + input (str): + The name of the stream input (as discussed + above). + """ + + input: str = proto.Field( + proto.STRING, + number=1, + ) + + class DebugOptions(proto.Message): + r"""Options available for debugging purposes only. + + Attributes: + environment_variables (MutableMapping[str, str]): + Environment variables. + """ + + environment_variables: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + + analyzer: str = proto.Field( + proto.STRING, + number=1, + ) + operator: str = proto.Field( + proto.STRING, + number=2, + ) + inputs: MutableSequence[StreamInput] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=StreamInput, + ) + attrs: MutableMapping[str, 'AttributeValue'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message='AttributeValue', + ) + debug_options: DebugOptions = proto.Field( + proto.MESSAGE, + number=5, + message=DebugOptions, + ) + + +class AnalysisDefinition(proto.Message): + r"""Defines a full analysis. + + This is a description of the overall live analytics pipeline. + You may think of this as an edge list representation of a + multigraph. + + This may be directly authored by a human in protobuf textformat, + or it may be generated by a programming API (perhaps Python or + JavaScript depending on context). + + Attributes: + analyzers (MutableSequence[google.cloud.visionai_v1alpha1.types.AnalyzerDefinition]): + Analyzer definitions. + """ + + analyzers: MutableSequence['AnalyzerDefinition'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnalyzerDefinition', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva_resources.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva_resources.py new file mode 100644 index 000000000000..ed38c23fea23 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva_resources.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1alpha1.types import lva +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'Analysis', + }, +) + + +class Analysis(proto.Message): + r"""Message describing the Analysis object. + + Attributes: + name (str): + The name of resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + analysis_definition (google.cloud.visionai_v1alpha1.types.AnalysisDefinition): + The definition of the analysis. + input_streams_mapping (MutableMapping[str, str]): + Map from the input parameter in the definition to the real + stream. E.g., suppose you had a stream source operator named + "input-0" and you try to receive from the real stream + "stream-0". You can add the following mapping: [input-0: + stream-0]. + output_streams_mapping (MutableMapping[str, str]): + Map from the output parameter in the definition to the real + stream. E.g., suppose you had a stream sink operator named + "output-0" and you try to send to the real stream + "stream-0". You can add the following mapping: [output-0: + stream-0]. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + analysis_definition: lva.AnalysisDefinition = proto.Field( + proto.MESSAGE, + number=5, + message=lva.AnalysisDefinition, + ) + input_streams_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + output_streams_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva_service.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva_service.py new file mode 100644 index 000000000000..115e10412383 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/lva_service.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'ListAnalysesRequest', + 'ListAnalysesResponse', + 'GetAnalysisRequest', + 'CreateAnalysisRequest', + 'UpdateAnalysisRequest', + 'DeleteAnalysisRequest', + }, +) + + +class ListAnalysesRequest(proto.Message): + r"""Message for requesting list of Analyses + + Attributes: + parent (str): + Required. Parent value for + ListAnalysesRequest + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAnalysesResponse(proto.Message): + r"""Message for response to listing Analyses + + Attributes: + analyses (MutableSequence[google.cloud.visionai_v1alpha1.types.Analysis]): + The list of Analysis + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + analyses: MutableSequence[lva_resources.Analysis] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=lva_resources.Analysis, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetAnalysisRequest(proto.Message): + r"""Message for getting an Analysis. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAnalysisRequest(proto.Message): + r"""Message for creating an Analysis. + + Attributes: + parent (str): + Required. Value for parent. + analysis_id (str): + Required. Id of the requesting object. + analysis (google.cloud.visionai_v1alpha1.types.Analysis): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + analysis_id: str = proto.Field( + proto.STRING, + number=2, + ) + analysis: lva_resources.Analysis = proto.Field( + proto.MESSAGE, + number=3, + message=lva_resources.Analysis, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateAnalysisRequest(proto.Message): + r"""Message for updating an Analysis. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Analysis resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + analysis (google.cloud.visionai_v1alpha1.types.Analysis): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + analysis: lva_resources.Analysis = proto.Field( + proto.MESSAGE, + number=2, + message=lva_resources.Analysis, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteAnalysisRequest(proto.Message): + r"""Message for deleting an Analysis. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/platform.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/platform.py new file mode 100644 index 000000000000..b796dc502353 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/platform.py @@ -0,0 +1,3408 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1alpha1.types import annotations as gcv_annotations +from google.cloud.visionai_v1alpha1.types import common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'ModelType', + 'AcceleratorType', + 'DeleteApplicationInstancesResponse', + 'CreateApplicationInstancesResponse', + 'UpdateApplicationInstancesResponse', + 'CreateApplicationInstancesRequest', + 'DeleteApplicationInstancesRequest', + 'DeployApplicationResponse', + 'UndeployApplicationResponse', + 'RemoveApplicationStreamInputResponse', + 'AddApplicationStreamInputResponse', + 'UpdateApplicationStreamInputResponse', + 'ListApplicationsRequest', + 'ListApplicationsResponse', + 'GetApplicationRequest', + 'CreateApplicationRequest', + 'UpdateApplicationRequest', + 'DeleteApplicationRequest', + 'DeployApplicationRequest', + 'UndeployApplicationRequest', + 'ApplicationStreamInput', + 'AddApplicationStreamInputRequest', + 'UpdateApplicationStreamInputRequest', + 'RemoveApplicationStreamInputRequest', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'GetInstanceRequest', + 'ListDraftsRequest', + 'ListDraftsResponse', + 'GetDraftRequest', + 'CreateDraftRequest', + 'UpdateDraftRequest', + 'UpdateApplicationInstancesRequest', + 'DeleteDraftRequest', + 'ListProcessorsRequest', + 'ListProcessorsResponse', + 'ListPrebuiltProcessorsRequest', + 'ListPrebuiltProcessorsResponse', + 'GetProcessorRequest', + 'CreateProcessorRequest', + 'UpdateProcessorRequest', + 'DeleteProcessorRequest', + 'Application', + 'ApplicationConfigs', + 'Node', + 'Draft', + 'Instance', + 'ApplicationInstance', + 'Processor', + 'ProcessorIOSpec', + 'CustomProcessorSourceInfo', + 'ProcessorConfig', + 'StreamWithAnnotation', + 'ApplicationNodeAnnotation', + 'ResourceAnnotations', + 'VideoStreamInputConfig', + 'AIEnabledDevicesInputConfig', + 'MediaWarehouseConfig', + 'PersonBlurConfig', + 'OccupancyCountConfig', + 'PersonVehicleDetectionConfig', + 'PersonalProtectiveEquipmentDetectionConfig', + 'GeneralObjectDetectionConfig', + 'BigQueryConfig', + 'VertexAutoMLVisionConfig', + 'VertexAutoMLVideoConfig', + 'VertexCustomConfig', + 'MachineSpec', + 'AutoscalingMetricSpec', + 'DedicatedResources', + }, +) + + +class ModelType(proto.Enum): + r"""All the supported model types in Vision AI App Platform. + + Values: + MODEL_TYPE_UNSPECIFIED (0): + Processor Type UNSPECIFIED. + IMAGE_CLASSIFICATION (1): + Model Type Image Classification. + OBJECT_DETECTION (2): + Model Type Object Detection. + VIDEO_CLASSIFICATION (3): + Model Type Video Classification. + VIDEO_OBJECT_TRACKING (4): + Model Type Object Tracking. + VIDEO_ACTION_RECOGNITION (5): + Model Type Action Recognition. + OCCUPANCY_COUNTING (6): + Model Type Occupancy Counting. + PERSON_BLUR (7): + Model Type Person Blur. + VERTEX_CUSTOM (8): + Model Type Vertex Custom. + """ + MODEL_TYPE_UNSPECIFIED = 0 + IMAGE_CLASSIFICATION = 1 + OBJECT_DETECTION = 2 + VIDEO_CLASSIFICATION = 3 + VIDEO_OBJECT_TRACKING = 4 + VIDEO_ACTION_RECOGNITION = 5 + OCCUPANCY_COUNTING = 6 + PERSON_BLUR = 7 + VERTEX_CUSTOM = 8 + + +class AcceleratorType(proto.Enum): + r"""Represents a hardware accelerator type. + + Values: + ACCELERATOR_TYPE_UNSPECIFIED (0): + Unspecified accelerator type, which means no + accelerator. + NVIDIA_TESLA_K80 (1): + Nvidia Tesla K80 GPU. + NVIDIA_TESLA_P100 (2): + Nvidia Tesla P100 GPU. + NVIDIA_TESLA_V100 (3): + Nvidia Tesla V100 GPU. + NVIDIA_TESLA_P4 (4): + Nvidia Tesla P4 GPU. + NVIDIA_TESLA_T4 (5): + Nvidia Tesla T4 GPU. + NVIDIA_TESLA_A100 (8): + Nvidia Tesla A100 GPU. + TPU_V2 (6): + TPU v2. + TPU_V3 (7): + TPU v3. + """ + ACCELERATOR_TYPE_UNSPECIFIED = 0 + NVIDIA_TESLA_K80 = 1 + NVIDIA_TESLA_P100 = 2 + NVIDIA_TESLA_V100 = 3 + NVIDIA_TESLA_P4 = 4 + NVIDIA_TESLA_T4 = 5 + NVIDIA_TESLA_A100 = 8 + TPU_V2 = 6 + TPU_V3 = 7 + + +class DeleteApplicationInstancesResponse(proto.Message): + r"""Message for DeleteApplicationInstance Response. + """ + + +class CreateApplicationInstancesResponse(proto.Message): + r"""Message for CreateApplicationInstance Response. + """ + + +class UpdateApplicationInstancesResponse(proto.Message): + r"""Message for UpdateApplicationInstances Response. + """ + + +class CreateApplicationInstancesRequest(proto.Message): + r"""Message for adding stream input to an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_instances (MutableSequence[google.cloud.visionai_v1alpha1.types.ApplicationInstance]): + Required. The resources being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_instances: MutableSequence['ApplicationInstance'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationInstance', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteApplicationInstancesRequest(proto.Message): + r"""Message for removing stream input from an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + instance_ids (MutableSequence[str]): + Required. Id of the requesting object. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + instance_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeployApplicationResponse(proto.Message): + r"""RPC Request Messages. + Message for DeployApplication Response. + + """ + + +class UndeployApplicationResponse(proto.Message): + r"""Message for UndeployApplication Response. + """ + + +class RemoveApplicationStreamInputResponse(proto.Message): + r"""Message for RemoveApplicationStreamInput Response. + """ + + +class AddApplicationStreamInputResponse(proto.Message): + r"""Message for AddApplicationStreamInput Response. + """ + + +class UpdateApplicationStreamInputResponse(proto.Message): + r"""Message for AddApplicationStreamInput Response. + """ + + +class ListApplicationsRequest(proto.Message): + r"""Message for requesting list of Applications. + + Attributes: + parent (str): + Required. Parent value for + ListApplicationsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListApplicationsResponse(proto.Message): + r"""Message for response to listing Applications. + + Attributes: + applications (MutableSequence[google.cloud.visionai_v1alpha1.types.Application]): + The list of Application. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + applications: MutableSequence['Application'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Application', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetApplicationRequest(proto.Message): + r"""Message for getting a Application. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateApplicationRequest(proto.Message): + r"""Message for creating a Application. + + Attributes: + parent (str): + Required. Value for parent. + application_id (str): + Required. Id of the requesting object. + application (google.cloud.visionai_v1alpha1.types.Application): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + application_id: str = proto.Field( + proto.STRING, + number=2, + ) + application: 'Application' = proto.Field( + proto.MESSAGE, + number=3, + message='Application', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateApplicationRequest(proto.Message): + r"""Message for updating an Application. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Application resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + application (google.cloud.visionai_v1alpha1.types.Application): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + application: 'Application' = proto.Field( + proto.MESSAGE, + number=2, + message='Application', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteApplicationRequest(proto.Message): + r"""Message for deleting an Application. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + force (bool): + Optional. If set to true, any instances and + drafts from this application will also be + deleted. (Otherwise, the request will only work + if the application has no instances and drafts.) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeployApplicationRequest(proto.Message): + r"""Message for deploying an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + validate_only (bool): + If set, validate the request and preview the + application graph, but do not actually deploy + it. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + enable_monitoring (bool): + Optional. Whether or not to enable monitoring + for the application on deployment. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + enable_monitoring: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UndeployApplicationRequest(proto.Message): + r"""Message for undeploying an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ApplicationStreamInput(proto.Message): + r"""Message about a single stream input config. + + Attributes: + stream_with_annotation (google.cloud.visionai_v1alpha1.types.StreamWithAnnotation): + + """ + + stream_with_annotation: 'StreamWithAnnotation' = proto.Field( + proto.MESSAGE, + number=1, + message='StreamWithAnnotation', + ) + + +class AddApplicationStreamInputRequest(proto.Message): + r"""Message for adding stream input to an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_stream_inputs (MutableSequence[google.cloud.visionai_v1alpha1.types.ApplicationStreamInput]): + The stream inputs to add, the stream resource + name is the key of each StreamInput, and it must + be unique within each application. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_stream_inputs: MutableSequence['ApplicationStreamInput'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationStreamInput', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateApplicationStreamInputRequest(proto.Message): + r"""Message for updating stream input to an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_stream_inputs (MutableSequence[google.cloud.visionai_v1alpha1.types.ApplicationStreamInput]): + The stream inputs to update, the stream + resource name is the key of each StreamInput, + and it must be unique within each application. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + allow_missing (bool): + If true, UpdateApplicationStreamInput will + insert stream input to application even if the + target stream is not included in the + application. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_stream_inputs: MutableSequence['ApplicationStreamInput'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationStreamInput', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RemoveApplicationStreamInputRequest(proto.Message): + r"""Message for removing stream input from an Application. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + target_stream_inputs (MutableSequence[google.cloud.visionai_v1alpha1.types.RemoveApplicationStreamInputRequest.TargetStreamInput]): + The target stream to remove. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + class TargetStreamInput(proto.Message): + r"""Message about target streamInput to remove. + + Attributes: + stream (str): + + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + target_stream_inputs: MutableSequence[TargetStreamInput] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=TargetStreamInput, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListInstancesRequest(proto.Message): + r"""Message for requesting list of Instances. + + Attributes: + parent (str): + Required. Parent value for + ListInstancesRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInstancesResponse(proto.Message): + r"""Message for response to listing Instances. + + Attributes: + instances (MutableSequence[google.cloud.visionai_v1alpha1.types.Instance]): + The list of Instance. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence['Instance'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Instance', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetInstanceRequest(proto.Message): + r"""Message for getting a Instance. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDraftsRequest(proto.Message): + r"""Message for requesting list of Drafts. + + Attributes: + parent (str): + Required. Parent value for ListDraftsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListDraftsResponse(proto.Message): + r"""Message for response to listing Drafts. + + Attributes: + drafts (MutableSequence[google.cloud.visionai_v1alpha1.types.Draft]): + The list of Draft. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + drafts: MutableSequence['Draft'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Draft', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetDraftRequest(proto.Message): + r"""Message for getting a Draft. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDraftRequest(proto.Message): + r"""Message for creating a Draft. + + Attributes: + parent (str): + Required. Value for parent. + draft_id (str): + Required. Id of the requesting object. + draft (google.cloud.visionai_v1alpha1.types.Draft): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + draft_id: str = proto.Field( + proto.STRING, + number=2, + ) + draft: 'Draft' = proto.Field( + proto.MESSAGE, + number=3, + message='Draft', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateDraftRequest(proto.Message): + r"""Message for updating an Draft. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + draft (google.cloud.visionai_v1alpha1.types.Draft): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + allow_missing (bool): + If true, UpdateDraftRequest will create one resource if the + target resource doesn't exist, this time, the field_mask + will be ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + draft: 'Draft' = proto.Field( + proto.MESSAGE, + number=2, + message='Draft', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateApplicationInstancesRequest(proto.Message): + r"""Message for updating an ApplicationInstance. + + Attributes: + name (str): + Required. the name of the application to + retrieve. Format: + + "projects/{project}/locations/{location}/applications/{application}". + application_instances (MutableSequence[google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]): + + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + allow_missing (bool): + If true, Update Request will create one resource if the + target resource doesn't exist, this time, the field_mask + will be ignored. + """ + + class UpdateApplicationInstance(proto.Message): + r""" + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Draft resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + instance (google.cloud.visionai_v1alpha1.types.Instance): + Required. The resource being updated. + instance_id (str): + Required. The id of the instance. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + instance: 'Instance' = proto.Field( + proto.MESSAGE, + number=2, + message='Instance', + ) + instance_id: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + application_instances: MutableSequence[UpdateApplicationInstance] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=UpdateApplicationInstance, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteDraftRequest(proto.Message): + r"""Message for deleting an Draft. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListProcessorsRequest(proto.Message): + r"""Message for requesting list of Processors. + + Attributes: + parent (str): + Required. Parent value for + ListProcessorsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListProcessorsResponse(proto.Message): + r"""Message for response to listing Processors. + + Attributes: + processors (MutableSequence[google.cloud.visionai_v1alpha1.types.Processor]): + The list of Processor. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + processors: MutableSequence['Processor'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Processor', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListPrebuiltProcessorsRequest(proto.Message): + r"""Request Message for listing Prebuilt Processors. + + Attributes: + parent (str): + Required. Parent path. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPrebuiltProcessorsResponse(proto.Message): + r"""Response Message for listing Prebuilt Processors. + + Attributes: + processors (MutableSequence[google.cloud.visionai_v1alpha1.types.Processor]): + The list of Processor. + """ + + processors: MutableSequence['Processor'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Processor', + ) + + +class GetProcessorRequest(proto.Message): + r"""Message for getting a Processor. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateProcessorRequest(proto.Message): + r"""Message for creating a Processor. + + Attributes: + parent (str): + Required. Value for parent. + processor_id (str): + Required. Id of the requesting object. + processor (google.cloud.visionai_v1alpha1.types.Processor): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + processor_id: str = proto.Field( + proto.STRING, + number=2, + ) + processor: 'Processor' = proto.Field( + proto.MESSAGE, + number=3, + message='Processor', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateProcessorRequest(proto.Message): + r"""Message for updating a Processor. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Processor resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + processor (google.cloud.visionai_v1alpha1.types.Processor): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + processor: 'Processor' = proto.Field( + proto.MESSAGE, + number=2, + message='Processor', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteProcessorRequest(proto.Message): + r"""Message for deleting a Processor. + + Attributes: + name (str): + Required. Name of the resource + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Application(proto.Message): + r"""Message describing Application object + + Attributes: + name (str): + name of resource + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update timestamp + labels (MutableMapping[str, str]): + Labels as key value pairs + display_name (str): + Required. A user friendly display name for + the solution. + description (str): + A description for this application. + application_configs (google.cloud.visionai_v1alpha1.types.ApplicationConfigs): + Application graph configuration. + runtime_info (google.cloud.visionai_v1alpha1.types.Application.ApplicationRuntimeInfo): + Output only. Application graph runtime info. + Only exists when application state equals to + DEPLOYED. + state (google.cloud.visionai_v1alpha1.types.Application.State): + Output only. State of the application. + """ + class State(proto.Enum): + r"""State of the Application + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + CREATED (1): + State CREATED. + DEPLOYING (2): + State DEPLOYING. + DEPLOYED (3): + State DEPLOYED. + UNDEPLOYING (4): + State UNDEPLOYING. + DELETED (5): + State DELETED. + ERROR (6): + State ERROR. + CREATING (7): + State CREATING. + UPDATING (8): + State Updating. + DELETING (9): + State Deleting. + FIXING (10): + State Fixing. + """ + STATE_UNSPECIFIED = 0 + CREATED = 1 + DEPLOYING = 2 + DEPLOYED = 3 + UNDEPLOYING = 4 + DELETED = 5 + ERROR = 6 + CREATING = 7 + UPDATING = 8 + DELETING = 9 + FIXING = 10 + + class ApplicationRuntimeInfo(proto.Message): + r"""Message storing the runtime information of the application. + + Attributes: + deploy_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the engine be deployed + global_output_resources (MutableSequence[google.cloud.visionai_v1alpha1.types.Application.ApplicationRuntimeInfo.GlobalOutputResource]): + Globally created resources like warehouse + dataschemas. + monitoring_config (google.cloud.visionai_v1alpha1.types.Application.ApplicationRuntimeInfo.MonitoringConfig): + Monitoring-related configuration for this + application. + """ + + class GlobalOutputResource(proto.Message): + r"""Message about output resources from application. + + Attributes: + output_resource (str): + The full resource name of the outputted + resources. + producer_node (str): + The name of graph node who produces the output resource + name. For example: output_resource: + /projects/123/locations/us-central1/corpora/my-corpus/dataSchemas/my-schema + producer_node: occupancy-count + key (str): + The key of the output resource, it has to be + unique within the same producer node. One + producer node can output several output + resources, the key can be used to match + corresponding output resources. + """ + + output_resource: str = proto.Field( + proto.STRING, + number=1, + ) + producer_node: str = proto.Field( + proto.STRING, + number=2, + ) + key: str = proto.Field( + proto.STRING, + number=3, + ) + + class MonitoringConfig(proto.Message): + r"""Monitoring-related configuration for an application. + + Attributes: + enabled (bool): + Whether this application has monitoring + enabled. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + deploy_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + global_output_resources: MutableSequence['Application.ApplicationRuntimeInfo.GlobalOutputResource'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Application.ApplicationRuntimeInfo.GlobalOutputResource', + ) + monitoring_config: 'Application.ApplicationRuntimeInfo.MonitoringConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='Application.ApplicationRuntimeInfo.MonitoringConfig', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + application_configs: 'ApplicationConfigs' = proto.Field( + proto.MESSAGE, + number=7, + message='ApplicationConfigs', + ) + runtime_info: ApplicationRuntimeInfo = proto.Field( + proto.MESSAGE, + number=8, + message=ApplicationRuntimeInfo, + ) + state: State = proto.Field( + proto.ENUM, + number=9, + enum=State, + ) + + +class ApplicationConfigs(proto.Message): + r"""Message storing the graph of the application. + + Attributes: + nodes (MutableSequence[google.cloud.visionai_v1alpha1.types.Node]): + A list of nodes in the application graph. + event_delivery_config (google.cloud.visionai_v1alpha1.types.ApplicationConfigs.EventDeliveryConfig): + Event-related configuration for this + application. + """ + + class EventDeliveryConfig(proto.Message): + r"""message storing the config for event delivery + + Attributes: + channel (str): + The delivery channel for the event notification, only + pub/sub topic is supported now. Example channel: + [//pubsub.googleapis.com/projects/visionai-testing-stable/topics/test-topic] + minimal_delivery_interval (google.protobuf.duration_pb2.Duration): + The expected delivery interval for the same event. The same + event won't be notified multiple times during this internal + event that it is happening multiple times during the period + of time.The same event is identified by . + """ + + channel: str = proto.Field( + proto.STRING, + number=1, + ) + minimal_delivery_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + nodes: MutableSequence['Node'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Node', + ) + event_delivery_config: EventDeliveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=EventDeliveryConfig, + ) + + +class Node(proto.Message): + r"""Message describing node object. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + output_all_output_channels_to_stream (bool): + By default, the output of the node will only be available to + downstream nodes. To consume the direct output from the + application node, the output must be sent to Vision AI + Streams at first. + + By setting output_all_output_channels_to_stream to true, App + Platform will automatically send all the outputs of the + current node to Vision AI Stream resources (one stream per + output channel). The output stream resource will be created + by App Platform automatically during deployment and deleted + after application un-deployment. Note that this config + applies to all the Application Instances. + + The output stream can be override at instance level by + configuring the ``output_resources`` section of Instance + resource. ``producer_node`` should be current node, + ``output_resource_binding`` should be the output channel + name (or leave it blank if there is only 1 output channel of + the processor) and ``output_resource`` should be the target + output stream. + + This field is a member of `oneof`_ ``stream_output_config``. + name (str): + Required. A unique name for the node. + display_name (str): + A user friendly display name for the node. + node_config (google.cloud.visionai_v1alpha1.types.ProcessorConfig): + Node config. + processor (str): + Processor name refer to the chosen processor + resource. + parents (MutableSequence[google.cloud.visionai_v1alpha1.types.Node.InputEdge]): + Parent node. Input node should not have + parent node. For V1 Alpha1/Beta only media + warehouse node can have multiple parents, other + types of nodes will only have one parent. + """ + + class InputEdge(proto.Message): + r"""Message describing one edge pointing into a node. + + Attributes: + parent_node (str): + The name of the parent node. + parent_output_channel (str): + The connected output artifact of the parent + node. It can be omitted if target processor only + has 1 output artifact. + connected_input_channel (str): + The connected input channel of the current + node's processor. It can be omitted if target + processor only has 1 input channel. + """ + + parent_node: str = proto.Field( + proto.STRING, + number=1, + ) + parent_output_channel: str = proto.Field( + proto.STRING, + number=2, + ) + connected_input_channel: str = proto.Field( + proto.STRING, + number=3, + ) + + output_all_output_channels_to_stream: bool = proto.Field( + proto.BOOL, + number=6, + oneof='stream_output_config', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + node_config: 'ProcessorConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='ProcessorConfig', + ) + processor: str = proto.Field( + proto.STRING, + number=4, + ) + parents: MutableSequence[InputEdge] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=InputEdge, + ) + + +class Draft(proto.Message): + r"""Message describing Draft object + + Attributes: + name (str): + name of resource + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + labels (MutableMapping[str, str]): + Labels as key value pairs + display_name (str): + Required. A user friendly display name for + the solution. + description (str): + A description for this application. + draft_application_configs (google.cloud.visionai_v1alpha1.types.ApplicationConfigs): + The draft application configs which haven't + been updated to an application. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + draft_application_configs: 'ApplicationConfigs' = proto.Field( + proto.MESSAGE, + number=6, + message='ApplicationConfigs', + ) + + +class Instance(proto.Message): + r"""Message describing Instance object + + Attributes: + name (str): + Output only. name of resource + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update timestamp + labels (MutableMapping[str, str]): + Labels as key value pairs + display_name (str): + Required. A user friendly display name for + the solution. + description (str): + A description for this application. + input_resources (MutableSequence[google.cloud.visionai_v1alpha1.types.Instance.InputResource]): + The input resources for the current application instance. + For example: input_resources: + visionai.googleapis.com/v1/projects/123/locations/us-central1/clusters/456/streams/stream-a + output_resources (MutableSequence[google.cloud.visionai_v1alpha1.types.Instance.OutputResource]): + All the output resources associated to one + application instance. + state (google.cloud.visionai_v1alpha1.types.Instance.State): + State of the instance. + """ + class State(proto.Enum): + r"""State of the Instance + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + CREATING (1): + State CREATING. + CREATED (2): + State CREATED. + DEPLOYING (3): + State DEPLOYING. + DEPLOYED (4): + State DEPLOYED. + UNDEPLOYING (5): + State UNDEPLOYING. + DELETED (6): + State DELETED. + ERROR (7): + State ERROR. + UPDATING (8): + State Updating + DELETING (9): + State Deleting. + FIXING (10): + State Fixing. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + CREATED = 2 + DEPLOYING = 3 + DEPLOYED = 4 + UNDEPLOYING = 5 + DELETED = 6 + ERROR = 7 + UPDATING = 8 + DELETING = 9 + FIXING = 10 + + class InputResource(proto.Message): + r"""Message of input resource used in one application instance. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + input_resource (str): + The direct input resource name. + + This field is a member of `oneof`_ ``input_resource_information``. + annotated_stream (google.cloud.visionai_v1alpha1.types.StreamWithAnnotation): + If the input resource is VisionAI Stream, the associated + annotations can be specified using annotated_stream instead. + + This field is a member of `oneof`_ ``input_resource_information``. + consumer_node (str): + The name of graph node who receives the input resource. For + example: input_resource: + visionai.googleapis.com/v1/projects/123/locations/us-central1/clusters/456/streams/input-stream-a + consumer_node: stream-input + input_resource_binding (str): + The specific input resource binding which + will consume the current Input Resource, can be + ignored is there is only 1 input binding. + annotations (google.cloud.visionai_v1alpha1.types.ResourceAnnotations): + Contains resource annotations. + """ + + input_resource: str = proto.Field( + proto.STRING, + number=1, + oneof='input_resource_information', + ) + annotated_stream: 'StreamWithAnnotation' = proto.Field( + proto.MESSAGE, + number=4, + oneof='input_resource_information', + message='StreamWithAnnotation', + ) + consumer_node: str = proto.Field( + proto.STRING, + number=2, + ) + input_resource_binding: str = proto.Field( + proto.STRING, + number=3, + ) + annotations: 'ResourceAnnotations' = proto.Field( + proto.MESSAGE, + number=5, + message='ResourceAnnotations', + ) + + class OutputResource(proto.Message): + r"""Message of output resource used in one application instance. + + Attributes: + output_resource (str): + The output resource name for the current + application instance. + producer_node (str): + The name of graph node who produces the output resource + name. For example: output_resource: + /projects/123/locations/us-central1/clusters/456/streams/output-application-789-stream-a-occupancy-counting + producer_node: occupancy-counting + output_resource_binding (str): + The specific output resource binding which + produces the current OutputResource. + is_temporary (bool): + Output only. Whether the output resource is + temporary which means the resource is generated + during the deployment of the application. + Temporary resource will be deleted during the + undeployment of the application. + autogen (bool): + Output only. Whether the output resource is + created automatically by the Vision AI App + Platform. + """ + + output_resource: str = proto.Field( + proto.STRING, + number=1, + ) + producer_node: str = proto.Field( + proto.STRING, + number=2, + ) + output_resource_binding: str = proto.Field( + proto.STRING, + number=4, + ) + is_temporary: bool = proto.Field( + proto.BOOL, + number=3, + ) + autogen: bool = proto.Field( + proto.BOOL, + number=5, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + input_resources: MutableSequence[InputResource] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=InputResource, + ) + output_resources: MutableSequence[OutputResource] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=OutputResource, + ) + state: State = proto.Field( + proto.ENUM, + number=9, + enum=State, + ) + + +class ApplicationInstance(proto.Message): + r"""Message for creating a Instance. + + Attributes: + instance_id (str): + Required. Id of the requesting object. + instance (google.cloud.visionai_v1alpha1.types.Instance): + Required. The resource being created. + """ + + instance_id: str = proto.Field( + proto.STRING, + number=1, + ) + instance: 'Instance' = proto.Field( + proto.MESSAGE, + number=2, + message='Instance', + ) + + +class Processor(proto.Message): + r"""Message describing Processor object. + Next ID: 18 + + Attributes: + name (str): + name of resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + display_name (str): + Required. A user friendly display name for + the processor. + description (str): + Illustrative sentences for describing the + functionality of the processor. + processor_type (google.cloud.visionai_v1alpha1.types.Processor.ProcessorType): + Output only. Processor Type. + model_type (google.cloud.visionai_v1alpha1.types.ModelType): + Model Type. + custom_processor_source_info (google.cloud.visionai_v1alpha1.types.CustomProcessorSourceInfo): + Source info for customer created processor. + state (google.cloud.visionai_v1alpha1.types.Processor.ProcessorState): + Output only. State of the Processor. + processor_io_spec (google.cloud.visionai_v1alpha1.types.ProcessorIOSpec): + Output only. [Output only] The input / output specifications + of a processor, each type of processor has fixed input / + output specs which cannot be altered by customer. + configuration_typeurl (str): + Output only. The corresponding configuration + can be used in the Application to customize the + behavior of the processor. + supported_annotation_types (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamAnnotationType]): + + supports_post_processing (bool): + Indicates if the processor supports post + processing. + """ + class ProcessorType(proto.Enum): + r"""Type + + Values: + PROCESSOR_TYPE_UNSPECIFIED (0): + Processor Type UNSPECIFIED. + PRETRAINED (1): + Processor Type PRETRAINED. + Pretrained processor is developed by Vision AI + App Platform with state-of-the-art vision data + processing functionality, like occupancy + counting or person blur. Pretrained processor is + usually publicly available. + CUSTOM (2): + Processor Type CUSTOM. + Custom processors are specialized processors + which are either uploaded by customers or + imported from other GCP platform (for example + Vertex AI). Custom processor is only visible to + the creator. + CONNECTOR (3): + Processor Type CONNECTOR. + Connector processors are special processors + which perform I/O for the application, they do + not processing the data but either deliver the + data to other processors or receive data from + other processors. + """ + PROCESSOR_TYPE_UNSPECIFIED = 0 + PRETRAINED = 1 + CUSTOM = 2 + CONNECTOR = 3 + + class ProcessorState(proto.Enum): + r""" + + Values: + PROCESSOR_STATE_UNSPECIFIED (0): + Unspecified Processor state. + CREATING (1): + Processor is being created (not ready for + use). + ACTIVE (2): + Processor is and ready for use. + DELETING (3): + Processor is being deleted (not ready for + use). + FAILED (4): + Processor deleted or creation failed . + """ + PROCESSOR_STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + FAILED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=10, + ) + processor_type: ProcessorType = proto.Field( + proto.ENUM, + number=6, + enum=ProcessorType, + ) + model_type: 'ModelType' = proto.Field( + proto.ENUM, + number=13, + enum='ModelType', + ) + custom_processor_source_info: 'CustomProcessorSourceInfo' = proto.Field( + proto.MESSAGE, + number=7, + message='CustomProcessorSourceInfo', + ) + state: ProcessorState = proto.Field( + proto.ENUM, + number=8, + enum=ProcessorState, + ) + processor_io_spec: 'ProcessorIOSpec' = proto.Field( + proto.MESSAGE, + number=11, + message='ProcessorIOSpec', + ) + configuration_typeurl: str = proto.Field( + proto.STRING, + number=14, + ) + supported_annotation_types: MutableSequence[gcv_annotations.StreamAnnotationType] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=gcv_annotations.StreamAnnotationType, + ) + supports_post_processing: bool = proto.Field( + proto.BOOL, + number=17, + ) + + +class ProcessorIOSpec(proto.Message): + r"""Message describing the input / output specifications of a + processor. + + Attributes: + graph_input_channel_specs (MutableSequence[google.cloud.visionai_v1alpha1.types.ProcessorIOSpec.GraphInputChannelSpec]): + For processors with input_channel_specs, the processor must + be explicitly connected to another processor. + graph_output_channel_specs (MutableSequence[google.cloud.visionai_v1alpha1.types.ProcessorIOSpec.GraphOutputChannelSpec]): + The output artifact specifications for the + current processor. + instance_resource_input_binding_specs (MutableSequence[google.cloud.visionai_v1alpha1.types.ProcessorIOSpec.InstanceResourceInputBindingSpec]): + The input resource that needs to be fed from + the application instance. + instance_resource_output_binding_specs (MutableSequence[google.cloud.visionai_v1alpha1.types.ProcessorIOSpec.InstanceResourceOutputBindingSpec]): + The output resource that the processor will + generate per instance. Other than the explicitly + listed output bindings here, all the processors' + GraphOutputChannels can be binded to stream + resource. The bind name then is the same as the + GraphOutputChannel's name. + """ + class DataType(proto.Enum): + r"""High level data types supported by the processor. + + Values: + DATA_TYPE_UNSPECIFIED (0): + The default value of DataType. + VIDEO (1): + Video data type like H264. + PROTO (2): + Protobuf data type, usually used for general + data blob. + """ + DATA_TYPE_UNSPECIFIED = 0 + VIDEO = 1 + PROTO = 2 + + class GraphInputChannelSpec(proto.Message): + r"""Message for input channel specification. + + Attributes: + name (str): + The name of the current input channel. + data_type (google.cloud.visionai_v1alpha1.types.ProcessorIOSpec.DataType): + The data types of the current input channel. + When this field has more than 1 value, it means + this input channel can be connected to either of + these different data types. + accepted_data_type_uris (MutableSequence[str]): + If specified, only those detailed data types + can be connected to the processor. For example, + jpeg stream for MEDIA, or PredictionResult proto + for PROTO type. If unspecified, then any proto + is accepted. + required (bool): + Whether the current input channel is required + by the processor. For example, for a processor + with required video input and optional audio + input, if video input is missing, the + application will be rejected while the audio + input can be missing as long as the video input + exists. + max_connection_allowed (int): + How many input edges can be connected to this + input channel. 0 means unlimited. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_type: 'ProcessorIOSpec.DataType' = proto.Field( + proto.ENUM, + number=2, + enum='ProcessorIOSpec.DataType', + ) + accepted_data_type_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + required: bool = proto.Field( + proto.BOOL, + number=3, + ) + max_connection_allowed: int = proto.Field( + proto.INT64, + number=4, + ) + + class GraphOutputChannelSpec(proto.Message): + r"""Message for output channel specification. + + Attributes: + name (str): + The name of the current output channel. + data_type (google.cloud.visionai_v1alpha1.types.ProcessorIOSpec.DataType): + The data type of the current output channel. + data_type_uri (str): + + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_type: 'ProcessorIOSpec.DataType' = proto.Field( + proto.ENUM, + number=2, + enum='ProcessorIOSpec.DataType', + ) + data_type_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + class InstanceResourceInputBindingSpec(proto.Message): + r"""Message for instance resource channel specification. + External resources are virtual nodes which are not expressed in + the application graph. Each processor expresses its out-graph + spec, so customer is able to override the external source or + destinations to the + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + config_type_uri (str): + The configuration proto that includes the + Googleapis resources. I.e. + type.googleapis.com/google.cloud.vision.v1.StreamWithAnnotation + + This field is a member of `oneof`_ ``resource_type``. + resource_type_uri (str): + The direct type url of Googleapis resource. + i.e. + type.googleapis.com/google.cloud.vision.v1.Asset + + This field is a member of `oneof`_ ``resource_type``. + name (str): + Name of the input binding, unique within the + processor. + """ + + config_type_uri: str = proto.Field( + proto.STRING, + number=2, + oneof='resource_type', + ) + resource_type_uri: str = proto.Field( + proto.STRING, + number=3, + oneof='resource_type', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class InstanceResourceOutputBindingSpec(proto.Message): + r""" + + Attributes: + name (str): + Name of the output binding, unique within the + processor. + resource_type_uri (str): + The resource type uri of the acceptable + output resource. + explicit (bool): + Whether the output resource needs to be + explicitly set in the instance. If it is false, + the processor will automatically generate it if + required. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type_uri: str = proto.Field( + proto.STRING, + number=2, + ) + explicit: bool = proto.Field( + proto.BOOL, + number=3, + ) + + graph_input_channel_specs: MutableSequence[GraphInputChannelSpec] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=GraphInputChannelSpec, + ) + graph_output_channel_specs: MutableSequence[GraphOutputChannelSpec] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=GraphOutputChannelSpec, + ) + instance_resource_input_binding_specs: MutableSequence[InstanceResourceInputBindingSpec] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=InstanceResourceInputBindingSpec, + ) + instance_resource_output_binding_specs: MutableSequence[InstanceResourceOutputBindingSpec] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=InstanceResourceOutputBindingSpec, + ) + + +class CustomProcessorSourceInfo(proto.Message): + r"""Describes the source info for a custom processor. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + vertex_model (str): + The resource name original model hosted in + the vertex AI platform. + + This field is a member of `oneof`_ ``artifact_path``. + source_type (google.cloud.visionai_v1alpha1.types.CustomProcessorSourceInfo.SourceType): + The original product which holds the custom + processor's functionality. + additional_info (MutableMapping[str, str]): + Output only. Additional info related to the + imported custom processor. Data is filled in by + app platform during the processor creation. + model_schema (google.cloud.visionai_v1alpha1.types.CustomProcessorSourceInfo.ModelSchema): + Model schema files which specifies the signature of the + model. For VERTEX_CUSTOM models, instances schema is + required. If instances schema is not specified during the + processor creation, VisionAI Platform will try to get it + from Vertex, if it doesn't exist, the creation will fail. + """ + class SourceType(proto.Enum): + r"""Source type of the imported custom processor. + + Values: + SOURCE_TYPE_UNSPECIFIED (0): + Source type unspecified. + VERTEX_AUTOML (1): + Custom processors coming from Vertex AutoML + product. + VERTEX_CUSTOM (2): + Custom processors coming from general custom + models from Vertex. + """ + SOURCE_TYPE_UNSPECIFIED = 0 + VERTEX_AUTOML = 1 + VERTEX_CUSTOM = 2 + + class ModelSchema(proto.Message): + r"""The schema is defined as an OpenAPI 3.0.2 `Schema + Object `__. + + Attributes: + instances_schema (google.cloud.visionai_v1alpha1.types.GcsSource): + Cloud Storage location to a YAML file that + defines the format of a single instance used in + prediction and explanation requests. + parameters_schema (google.cloud.visionai_v1alpha1.types.GcsSource): + Cloud Storage location to a YAML file that + defines the prediction and explanation + parameters. + predictions_schema (google.cloud.visionai_v1alpha1.types.GcsSource): + Cloud Storage location to a YAML file that + defines the format of a single prediction or + explanation. + """ + + instances_schema: common.GcsSource = proto.Field( + proto.MESSAGE, + number=1, + message=common.GcsSource, + ) + parameters_schema: common.GcsSource = proto.Field( + proto.MESSAGE, + number=2, + message=common.GcsSource, + ) + predictions_schema: common.GcsSource = proto.Field( + proto.MESSAGE, + number=3, + message=common.GcsSource, + ) + + vertex_model: str = proto.Field( + proto.STRING, + number=2, + oneof='artifact_path', + ) + source_type: SourceType = proto.Field( + proto.ENUM, + number=1, + enum=SourceType, + ) + additional_info: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + model_schema: ModelSchema = proto.Field( + proto.MESSAGE, + number=5, + message=ModelSchema, + ) + + +class ProcessorConfig(proto.Message): + r"""Next ID: 24 + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + video_stream_input_config (google.cloud.visionai_v1alpha1.types.VideoStreamInputConfig): + Configs of stream input processor. + + This field is a member of `oneof`_ ``processor_config``. + ai_enabled_devices_input_config (google.cloud.visionai_v1alpha1.types.AIEnabledDevicesInputConfig): + Config of AI-enabled input devices. + + This field is a member of `oneof`_ ``processor_config``. + media_warehouse_config (google.cloud.visionai_v1alpha1.types.MediaWarehouseConfig): + Configs of media warehouse processor. + + This field is a member of `oneof`_ ``processor_config``. + person_blur_config (google.cloud.visionai_v1alpha1.types.PersonBlurConfig): + Configs of person blur processor. + + This field is a member of `oneof`_ ``processor_config``. + occupancy_count_config (google.cloud.visionai_v1alpha1.types.OccupancyCountConfig): + Configs of occupancy count processor. + + This field is a member of `oneof`_ ``processor_config``. + person_vehicle_detection_config (google.cloud.visionai_v1alpha1.types.PersonVehicleDetectionConfig): + Configs of Person Vehicle Detection + processor. + + This field is a member of `oneof`_ ``processor_config``. + vertex_automl_vision_config (google.cloud.visionai_v1alpha1.types.VertexAutoMLVisionConfig): + Configs of Vertex AutoML vision processor. + + This field is a member of `oneof`_ ``processor_config``. + vertex_automl_video_config (google.cloud.visionai_v1alpha1.types.VertexAutoMLVideoConfig): + Configs of Vertex AutoML video processor. + + This field is a member of `oneof`_ ``processor_config``. + vertex_custom_config (google.cloud.visionai_v1alpha1.types.VertexCustomConfig): + Configs of Vertex Custom processor. + + This field is a member of `oneof`_ ``processor_config``. + general_object_detection_config (google.cloud.visionai_v1alpha1.types.GeneralObjectDetectionConfig): + Configs of General Object Detection + processor. + + This field is a member of `oneof`_ ``processor_config``. + big_query_config (google.cloud.visionai_v1alpha1.types.BigQueryConfig): + Configs of BigQuery processor. + + This field is a member of `oneof`_ ``processor_config``. + personal_protective_equipment_detection_config (google.cloud.visionai_v1alpha1.types.PersonalProtectiveEquipmentDetectionConfig): + Configs of personal_protective_equipment_detection_config + + This field is a member of `oneof`_ ``processor_config``. + """ + + video_stream_input_config: 'VideoStreamInputConfig' = proto.Field( + proto.MESSAGE, + number=9, + oneof='processor_config', + message='VideoStreamInputConfig', + ) + ai_enabled_devices_input_config: 'AIEnabledDevicesInputConfig' = proto.Field( + proto.MESSAGE, + number=20, + oneof='processor_config', + message='AIEnabledDevicesInputConfig', + ) + media_warehouse_config: 'MediaWarehouseConfig' = proto.Field( + proto.MESSAGE, + number=10, + oneof='processor_config', + message='MediaWarehouseConfig', + ) + person_blur_config: 'PersonBlurConfig' = proto.Field( + proto.MESSAGE, + number=11, + oneof='processor_config', + message='PersonBlurConfig', + ) + occupancy_count_config: 'OccupancyCountConfig' = proto.Field( + proto.MESSAGE, + number=12, + oneof='processor_config', + message='OccupancyCountConfig', + ) + person_vehicle_detection_config: 'PersonVehicleDetectionConfig' = proto.Field( + proto.MESSAGE, + number=15, + oneof='processor_config', + message='PersonVehicleDetectionConfig', + ) + vertex_automl_vision_config: 'VertexAutoMLVisionConfig' = proto.Field( + proto.MESSAGE, + number=13, + oneof='processor_config', + message='VertexAutoMLVisionConfig', + ) + vertex_automl_video_config: 'VertexAutoMLVideoConfig' = proto.Field( + proto.MESSAGE, + number=14, + oneof='processor_config', + message='VertexAutoMLVideoConfig', + ) + vertex_custom_config: 'VertexCustomConfig' = proto.Field( + proto.MESSAGE, + number=17, + oneof='processor_config', + message='VertexCustomConfig', + ) + general_object_detection_config: 'GeneralObjectDetectionConfig' = proto.Field( + proto.MESSAGE, + number=18, + oneof='processor_config', + message='GeneralObjectDetectionConfig', + ) + big_query_config: 'BigQueryConfig' = proto.Field( + proto.MESSAGE, + number=19, + oneof='processor_config', + message='BigQueryConfig', + ) + personal_protective_equipment_detection_config: 'PersonalProtectiveEquipmentDetectionConfig' = proto.Field( + proto.MESSAGE, + number=22, + oneof='processor_config', + message='PersonalProtectiveEquipmentDetectionConfig', + ) + + +class StreamWithAnnotation(proto.Message): + r"""Message describing Vision AI stream with application specific + annotations. All the StreamAnnotation object inside this message + MUST have unique id. + + Attributes: + stream (str): + Vision AI Stream resource name. + application_annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamAnnotation]): + Annotations that will be applied to the whole + application. + node_annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamWithAnnotation.NodeAnnotation]): + Annotations that will be applied to the + specific node of the application. If the same + type of the annotations is applied to both + application and node, the node annotation will + be added in addition to the global application + one. + For example, if there is one active zone + annotation for the whole application and one + active zone annotation for the Occupancy + Analytic processor, then the Occupancy Analytic + processor will have two active zones defined. + """ + + class NodeAnnotation(proto.Message): + r"""Message describing annotations specific to application node. + + Attributes: + node (str): + The node name of the application graph. + annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamAnnotation]): + The node specific stream annotations. + """ + + node: str = proto.Field( + proto.STRING, + number=1, + ) + annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcv_annotations.StreamAnnotation, + ) + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + application_annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcv_annotations.StreamAnnotation, + ) + node_annotations: MutableSequence[NodeAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=NodeAnnotation, + ) + + +class ApplicationNodeAnnotation(proto.Message): + r"""Message describing annotations specific to application node. + This message is a duplication of + StreamWithAnnotation.NodeAnnotation. + + Attributes: + node (str): + The node name of the application graph. + annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamAnnotation]): + The node specific stream annotations. + """ + + node: str = proto.Field( + proto.STRING, + number=1, + ) + annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcv_annotations.StreamAnnotation, + ) + + +class ResourceAnnotations(proto.Message): + r"""Message describing general annotation for resources. + + Attributes: + application_annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamAnnotation]): + Annotations that will be applied to the whole + application. + node_annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.ApplicationNodeAnnotation]): + Annotations that will be applied to the + specific node of the application. If the same + type of the annotations is applied to both + application and node, the node annotation will + be added in addition to the global application + one. + For example, if there is one active zone + annotation for the whole application and one + active zone annotation for the Occupancy + Analytic processor, then the Occupancy Analytic + processor will have two active zones defined. + """ + + application_annotations: MutableSequence[gcv_annotations.StreamAnnotation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcv_annotations.StreamAnnotation, + ) + node_annotations: MutableSequence['ApplicationNodeAnnotation'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ApplicationNodeAnnotation', + ) + + +class VideoStreamInputConfig(proto.Message): + r"""Message describing Video Stream Input Config. + This message should only be used as a placeholder for + builtin:stream-input processor, actual stream binding should be + specified using corresponding API. + + Attributes: + streams (MutableSequence[str]): + + streams_with_annotation (MutableSequence[google.cloud.visionai_v1alpha1.types.StreamWithAnnotation]): + + """ + + streams: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + streams_with_annotation: MutableSequence['StreamWithAnnotation'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='StreamWithAnnotation', + ) + + +class AIEnabledDevicesInputConfig(proto.Message): + r"""Message describing AI-enabled Devices Input Config. + """ + + +class MediaWarehouseConfig(proto.Message): + r"""Message describing MediaWarehouseConfig. + + Attributes: + corpus (str): + Resource name of the Media Warehouse corpus. Format: + projects/${project_id}/locations/${location_id}/corpora/${corpus_id} + region (str): + Deprecated. + ttl (google.protobuf.duration_pb2.Duration): + The duration for which all media assets, + associated metadata, and search documents can + exist. + """ + + corpus: str = proto.Field( + proto.STRING, + number=1, + ) + region: str = proto.Field( + proto.STRING, + number=2, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + +class PersonBlurConfig(proto.Message): + r"""Message describing FaceBlurConfig. + + Attributes: + person_blur_type (google.cloud.visionai_v1alpha1.types.PersonBlurConfig.PersonBlurType): + Person blur type. + faces_only (bool): + Whether only blur faces other than the whole + object in the processor. + """ + class PersonBlurType(proto.Enum): + r"""Type of Person Blur + + Values: + PERSON_BLUR_TYPE_UNSPECIFIED (0): + PersonBlur Type UNSPECIFIED. + FULL_OCCULUSION (1): + FaceBlur Type full occlusion. + BLUR_FILTER (2): + FaceBlur Type blur filter. + """ + PERSON_BLUR_TYPE_UNSPECIFIED = 0 + FULL_OCCULUSION = 1 + BLUR_FILTER = 2 + + person_blur_type: PersonBlurType = proto.Field( + proto.ENUM, + number=1, + enum=PersonBlurType, + ) + faces_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class OccupancyCountConfig(proto.Message): + r"""Message describing OccupancyCountConfig. + + Attributes: + enable_people_counting (bool): + Whether to count the appearances of people, + output counts have 'people' as the key. + enable_vehicle_counting (bool): + Whether to count the appearances of vehicles, + output counts will have 'vehicle' as the key. + enable_dwelling_time_tracking (bool): + Whether to track each invidual object's + loitering time inside the scene or specific + zone. + """ + + enable_people_counting: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vehicle_counting: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_dwelling_time_tracking: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PersonVehicleDetectionConfig(proto.Message): + r"""Message describing PersonVehicleDetectionConfig. + + Attributes: + enable_people_counting (bool): + At least one of enable_people_counting and + enable_vehicle_counting fields must be set to true. Whether + to count the appearances of people, output counts have + 'people' as the key. + enable_vehicle_counting (bool): + Whether to count the appearances of vehicles, + output counts will have 'vehicle' as the key. + """ + + enable_people_counting: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vehicle_counting: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class PersonalProtectiveEquipmentDetectionConfig(proto.Message): + r"""Message describing + PersonalProtectiveEquipmentDetectionConfig. + + Attributes: + enable_face_coverage_detection (bool): + Whether to enable face coverage detection. + enable_head_coverage_detection (bool): + Whether to enable head coverage detection. + enable_hands_coverage_detection (bool): + Whether to enable hands coverage detection. + """ + + enable_face_coverage_detection: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_head_coverage_detection: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_hands_coverage_detection: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GeneralObjectDetectionConfig(proto.Message): + r"""Message of configurations for General Object Detection + processor. + + """ + + +class BigQueryConfig(proto.Message): + r"""Message of configurations for BigQuery processor. + + Attributes: + table (str): + BigQuery table resource for Vision AI + Platform to ingest annotations to. + cloud_function_mapping (MutableMapping[str, str]): + Data Schema By default, Vision AI Application will try to + write annotations to the target BigQuery table using the + following schema: + + ingestion_time: TIMESTAMP, the ingestion time of the + original data. + + application: STRING, name of the application which produces + the annotation. + + instance: STRING, Id of the instance which produces the + annotation. + + node: STRING, name of the application graph node which + produces the annotation. + + annotation: STRING or JSON, the actual annotation protobuf + will be converted to json string with bytes field as 64 + encoded string. It can be written to both String or Json + type column. + + To forward annotation data to an existing BigQuery table, + customer needs to make sure the compatibility of the schema. + The map maps application node name to its corresponding + cloud function endpoint to transform the annotations + directly to the + google.cloud.bigquery.storage.v1.AppendRowsRequest (only + avro_rows or proto_rows should be set). If configured, + annotations produced by corresponding application node will + sent to the Cloud Function at first before be forwarded to + BigQuery. + + If the default table schema doesn't fit, customer is able to + transform the annotation output from Vision AI Application + to arbitrary BigQuery table schema with CloudFunction. + + - The cloud function will receive + AppPlatformCloudFunctionRequest where the annotations + field will be the json format of Vision AI annotation. + - The cloud function should return + AppPlatformCloudFunctionResponse with AppendRowsRequest + stored in the annotations field. + - To drop the annotation, simply clear the annotations + field in the returned AppPlatformCloudFunctionResponse. + create_default_table_if_not_exists (bool): + If true, App Platform will create the + BigQuery DataSet and the BigQuery Table with + default schema if the specified table doesn't + exist. This doesn't work if any cloud function + customized schema is specified since the system + doesn't know your desired schema. JSON column + will be used in the default table created by App + Platform. + """ + + table: str = proto.Field( + proto.STRING, + number=1, + ) + cloud_function_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + create_default_table_if_not_exists: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class VertexAutoMLVisionConfig(proto.Message): + r"""Message of configurations of Vertex AutoML Vision Processors. + + Attributes: + confidence_threshold (float): + Only entities with higher score than the + threshold will be returned. Value 0.0 means to + return all the detected entities. + max_predictions (int): + At most this many predictions will be + returned per output frame. Value 0 means to + return all the detected entities. + """ + + confidence_threshold: float = proto.Field( + proto.FLOAT, + number=1, + ) + max_predictions: int = proto.Field( + proto.INT32, + number=2, + ) + + +class VertexAutoMLVideoConfig(proto.Message): + r"""Message describing VertexAutoMLVideoConfig. + + Attributes: + confidence_threshold (float): + Only entities with higher score than the + threshold will be returned. Value 0.0 means + returns all the detected entities. + blocked_labels (MutableSequence[str]): + Labels specified in this field won't be + returned. + max_predictions (int): + At most this many predictions will be + returned per output frame. Value 0 means to + return all the detected entities. + bounding_box_size_limit (float): + Only Bounding Box whose size is larger than + this limit will be returned. Object Tracking + only. Value 0.0 means to return all the detected + entities. + """ + + confidence_threshold: float = proto.Field( + proto.FLOAT, + number=1, + ) + blocked_labels: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + max_predictions: int = proto.Field( + proto.INT32, + number=3, + ) + bounding_box_size_limit: float = proto.Field( + proto.FLOAT, + number=4, + ) + + +class VertexCustomConfig(proto.Message): + r"""Message describing VertexCustomConfig. + + Attributes: + max_prediction_fps (int): + The max prediction frame per second. This + attribute sets how fast the operator sends + prediction requests to Vertex AI endpoint. + Default value is 0, which means there is no max + prediction fps limit. The operator sends + prediction requests at input fps. + dedicated_resources (google.cloud.visionai_v1alpha1.types.DedicatedResources): + A description of resources that are dedicated + to the DeployedModel, and that need a higher + degree of manual configuration. + post_processing_cloud_function (str): + If not empty, the prediction result will be sent to the + specified cloud function for post processing. + + - The cloud function will receive + AppPlatformCloudFunctionRequest where the annotations + field will be the json format of proto PredictResponse. + - The cloud function should return + AppPlatformCloudFunctionResponse with PredictResponse + stored in the annotations field. + - To drop the prediction output, simply clear the payload + field in the returned AppPlatformCloudFunctionResponse. + attach_application_metadata (bool): + If true, the prediction request received by + custom model will also contain metadata with the + following schema: + + 'appPlatformMetadata': { + 'ingestionTime': DOUBLE; (UNIX timestamp) + 'application': STRING; + 'instanceId': STRING; + 'node': STRING; + 'processor': STRING; + } + """ + + max_prediction_fps: int = proto.Field( + proto.INT32, + number=1, + ) + dedicated_resources: 'DedicatedResources' = proto.Field( + proto.MESSAGE, + number=2, + message='DedicatedResources', + ) + post_processing_cloud_function: str = proto.Field( + proto.STRING, + number=3, + ) + attach_application_metadata: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class MachineSpec(proto.Message): + r"""Specification of a single machine. + + Attributes: + machine_type (str): + Immutable. The type of the machine. + + See the `list of machine types supported for + prediction `__ + + See the `list of machine types supported for custom + training `__. + + For [DeployedModel][] this field is optional, and the + default value is ``n1-standard-2``. For + [BatchPredictionJob][] or as part of [WorkerPoolSpec][] this + field is required. + accelerator_type (google.cloud.visionai_v1alpha1.types.AcceleratorType): + Immutable. The type of accelerator(s) that may be attached + to the machine as per + [accelerator_count][google.cloud.visionai.v1alpha1.MachineSpec.accelerator_count]. + accelerator_count (int): + The number of accelerators to attach to the + machine. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + accelerator_type: 'AcceleratorType' = proto.Field( + proto.ENUM, + number=2, + enum='AcceleratorType', + ) + accelerator_count: int = proto.Field( + proto.INT32, + number=3, + ) + + +class AutoscalingMetricSpec(proto.Message): + r"""The metric specification that defines the target resource + utilization (CPU utilization, accelerator's duty cycle, and so + on) for calculating the desired replica count. + + Attributes: + metric_name (str): + Required. The resource metric name. Supported metrics: + + - For Online Prediction: + - ``aiplatform.googleapis.com/prediction/online/accelerator/duty_cycle`` + - ``aiplatform.googleapis.com/prediction/online/cpu/utilization`` + target (int): + The target resource utilization in percentage + (1% - 100%) for the given metric; once the real + usage deviates from the target by a certain + percentage, the machine replicas change. The + default value is 60 (representing 60%) if not + provided. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + target: int = proto.Field( + proto.INT32, + number=2, + ) + + +class DedicatedResources(proto.Message): + r"""A description of resources that are dedicated to a + DeployedModel, and that need a higher degree of manual + configuration. + + Attributes: + machine_spec (google.cloud.visionai_v1alpha1.types.MachineSpec): + Required. Immutable. The specification of a + single machine used by the prediction. + min_replica_count (int): + Required. Immutable. The minimum number of + machine replicas this DeployedModel will be + always deployed on. This value must be greater + than or equal to 1. + + If traffic against the DeployedModel increases, + it may dynamically be deployed onto more + replicas, and as traffic decreases, some of + these extra replicas may be freed. + max_replica_count (int): + Immutable. The maximum number of replicas this DeployedModel + may be deployed on when the traffic against it increases. If + the requested value is too large, the deployment will error, + but if deployment succeeds then the ability to scale the + model to that many replicas is guaranteed (barring service + outages). If traffic against the DeployedModel increases + beyond what its replicas at maximum may handle, a portion of + the traffic will be dropped. If this value is not provided, + will use + [min_replica_count][google.cloud.visionai.v1alpha1.DedicatedResources.min_replica_count] + as the default value. + + The value of this field impacts the charge against Vertex + CPU and GPU quotas. Specifically, you will be charged for + max_replica_count \* number of cores in the selected machine + type) and (max_replica_count \* number of GPUs per replica + in the selected machine type). + autoscaling_metric_specs (MutableSequence[google.cloud.visionai_v1alpha1.types.AutoscalingMetricSpec]): + Immutable. The metric specifications that overrides a + resource utilization metric (CPU utilization, accelerator's + duty cycle, and so on) target value (default to 60 if not + set). At most one entry is allowed per metric. + + If + [machine_spec.accelerator_count][google.cloud.visionai.v1alpha1.MachineSpec.accelerator_count] + is above 0, the autoscaling will be based on both CPU + utilization and accelerator's duty cycle metrics and scale + up when either metrics exceeds its target value while scale + down if both metrics are under their target value. The + default target value is 60 for both metrics. + + If + [machine_spec.accelerator_count][google.cloud.visionai.v1alpha1.MachineSpec.accelerator_count] + is 0, the autoscaling will be based on CPU utilization + metric only with default target value 60 if not explicitly + set. + + For example, in the case of Online Prediction, if you want + to override target CPU utilization to 80, you should set + [autoscaling_metric_specs.metric_name][google.cloud.visionai.v1alpha1.AutoscalingMetricSpec.metric_name] + to + ``aiplatform.googleapis.com/prediction/online/cpu/utilization`` + and + [autoscaling_metric_specs.target][google.cloud.visionai.v1alpha1.AutoscalingMetricSpec.target] + to ``80``. + """ + + machine_spec: 'MachineSpec' = proto.Field( + proto.MESSAGE, + number=1, + message='MachineSpec', + ) + min_replica_count: int = proto.Field( + proto.INT32, + number=2, + ) + max_replica_count: int = proto.Field( + proto.INT32, + number=3, + ) + autoscaling_metric_specs: MutableSequence['AutoscalingMetricSpec'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AutoscalingMetricSpec', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streaming_resources.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streaming_resources.py new file mode 100644 index 000000000000..347228f4acc8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streaming_resources.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'GstreamerBufferDescriptor', + 'RawImageDescriptor', + 'PacketType', + 'ServerMetadata', + 'SeriesMetadata', + 'PacketHeader', + 'Packet', + }, +) + + +class GstreamerBufferDescriptor(proto.Message): + r"""The descriptor for a gstreamer buffer payload. + + Attributes: + caps_string (str): + The caps string of the payload. + is_key_frame (bool): + Whether the buffer is a key frame. + pts_time (google.protobuf.timestamp_pb2.Timestamp): + PTS of the frame. + dts_time (google.protobuf.timestamp_pb2.Timestamp): + DTS of the frame. + duration (google.protobuf.duration_pb2.Duration): + Duration of the frame. + """ + + caps_string: str = proto.Field( + proto.STRING, + number=1, + ) + is_key_frame: bool = proto.Field( + proto.BOOL, + number=2, + ) + pts_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + dts_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + +class RawImageDescriptor(proto.Message): + r"""The descriptor for a raw image. + + Attributes: + format_ (str): + Raw image format. Its possible values are: + "srgb". + height (int): + The height of the image. + width (int): + The width of the image. + """ + + format_: str = proto.Field( + proto.STRING, + number=1, + ) + height: int = proto.Field( + proto.INT32, + number=2, + ) + width: int = proto.Field( + proto.INT32, + number=3, + ) + + +class PacketType(proto.Message): + r"""The message that represents the data type of a packet. + + Attributes: + type_class (str): + The type class of the packet. Its possible + values are: "gst", "protobuf", and "string". + type_descriptor (google.cloud.visionai_v1alpha1.types.PacketType.TypeDescriptor): + The type descriptor. + """ + + class TypeDescriptor(proto.Message): + r"""The message that fully specifies the type of the packet. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gstreamer_buffer_descriptor (google.cloud.visionai_v1alpha1.types.GstreamerBufferDescriptor): + GstreamerBufferDescriptor is the descriptor + for gstreamer buffer type. + + This field is a member of `oneof`_ ``type_details``. + raw_image_descriptor (google.cloud.visionai_v1alpha1.types.RawImageDescriptor): + RawImageDescriptor is the descriptor for the + raw image type. + + This field is a member of `oneof`_ ``type_details``. + type_ (str): + The type of the packet. Its possible values is codec + dependent. + + The fully qualified type name is always the concatenation of + the value in ``type_class`` together with the value in + ``type``, separated by a '/'. + + Note that specific codecs can define their own type + hierarchy, and so the type string here can in fact be + separated by multiple '/'s of its own. + + Please see the open source SDK for specific codec + documentation. + """ + + gstreamer_buffer_descriptor: 'GstreamerBufferDescriptor' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type_details', + message='GstreamerBufferDescriptor', + ) + raw_image_descriptor: 'RawImageDescriptor' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type_details', + message='RawImageDescriptor', + ) + type_: str = proto.Field( + proto.STRING, + number=1, + ) + + type_class: str = proto.Field( + proto.STRING, + number=1, + ) + type_descriptor: TypeDescriptor = proto.Field( + proto.MESSAGE, + number=2, + message=TypeDescriptor, + ) + + +class ServerMetadata(proto.Message): + r"""The message that represents server metadata. + + Attributes: + offset (int): + The offset position for the packet in its + stream. + ingest_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the stream server + receives this packet. This is based on the local + clock of on the server side. It is guaranteed to + be monotonically increasing for the packets + within each session; however this timestamp is + not comparable across packets sent to the same + stream different sessions. Session here refers + to one individual gRPC streaming request to the + stream server. + """ + + offset: int = proto.Field( + proto.INT64, + number=1, + ) + ingest_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class SeriesMetadata(proto.Message): + r"""The message that represents series metadata. + + Attributes: + series (str): + Series name. It's in the format of + "projects/{project}/locations/{location}/clusters/{cluster}/series/{stream}". + """ + + series: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PacketHeader(proto.Message): + r"""The message that represents packet header. + + Attributes: + capture_time (google.protobuf.timestamp_pb2.Timestamp): + Input only. The capture time of the packet. + type_ (google.cloud.visionai_v1alpha1.types.PacketType): + Input only. Immutable. The type of the + payload. + metadata (google.protobuf.struct_pb2.Struct): + Input only. This field is for users to attach + user managed metadata. + server_metadata (google.cloud.visionai_v1alpha1.types.ServerMetadata): + Output only. Metadata that the server appends + to each packet before sending it to receivers. + You don't need to set a value for this field + when sending packets. + series_metadata (google.cloud.visionai_v1alpha1.types.SeriesMetadata): + Input only. Immutable. Metadata that the + server needs to know where to write the packets + to. It's only required for the first packet. + flags (int): + Immutable. Packet flag set. SDK will set the + flag automatically. + trace_context (str): + Immutable. Header string for tracing across services. It + should be set when the packet is first arrived in the stream + server. + + The input format is a lowercase hex string: + + - version_id: 1 byte, currently must be zero - hex encoded + (2 characters) + - trace_id: 16 bytes (opaque blob) - hex encoded (32 + characters) + - span_id: 8 bytes (opaque blob) - hex encoded (16 + characters) + - trace_options: 1 byte (LSB means tracing enabled) - hex + encoded (2 characters) Example: + "00-404142434445464748494a4b4c4d4e4f-6162636465666768-01" + v trace_id span_id options + """ + + capture_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + type_: 'PacketType' = proto.Field( + proto.MESSAGE, + number=2, + message='PacketType', + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + server_metadata: 'ServerMetadata' = proto.Field( + proto.MESSAGE, + number=4, + message='ServerMetadata', + ) + series_metadata: 'SeriesMetadata' = proto.Field( + proto.MESSAGE, + number=5, + message='SeriesMetadata', + ) + flags: int = proto.Field( + proto.INT32, + number=6, + ) + trace_context: str = proto.Field( + proto.STRING, + number=7, + ) + + +class Packet(proto.Message): + r"""The quanta of datum that the series accepts. + + Attributes: + header (google.cloud.visionai_v1alpha1.types.PacketHeader): + The packet header. + payload (bytes): + The payload of the packet. + """ + + header: 'PacketHeader' = proto.Field( + proto.MESSAGE, + number=1, + message='PacketHeader', + ) + payload: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streaming_service.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streaming_service.py new file mode 100644 index 000000000000..43209e0e39d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streaming_service.py @@ -0,0 +1,780 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1alpha1.types import streaming_resources +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'LeaseType', + 'ReceiveEventsRequest', + 'EventUpdate', + 'ReceiveEventsControlResponse', + 'ReceiveEventsResponse', + 'Lease', + 'AcquireLeaseRequest', + 'RenewLeaseRequest', + 'ReleaseLeaseRequest', + 'ReleaseLeaseResponse', + 'RequestMetadata', + 'SendPacketsRequest', + 'SendPacketsResponse', + 'ReceivePacketsRequest', + 'ReceivePacketsControlResponse', + 'ReceivePacketsResponse', + 'EagerMode', + 'ControlledMode', + 'CommitRequest', + }, +) + + +class LeaseType(proto.Enum): + r"""The lease type. + + Values: + LEASE_TYPE_UNSPECIFIED (0): + Lease type unspecified. + LEASE_TYPE_READER (1): + Lease for stream reader. + LEASE_TYPE_WRITER (2): + Lease for stream writer. + """ + LEASE_TYPE_UNSPECIFIED = 0 + LEASE_TYPE_READER = 1 + LEASE_TYPE_WRITER = 2 + + +class ReceiveEventsRequest(proto.Message): + r"""Request message for ReceiveEvents. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + setup_request (google.cloud.visionai_v1alpha1.types.ReceiveEventsRequest.SetupRequest): + The setup request to setup the RPC + connection. + + This field is a member of `oneof`_ ``request``. + commit_request (google.cloud.visionai_v1alpha1.types.CommitRequest): + This request checkpoints the consumer's read + progress. + + This field is a member of `oneof`_ ``request``. + """ + + class SetupRequest(proto.Message): + r"""SetupRequest is the first message sent to the service to + setup the RPC connection. + + Attributes: + cluster (str): + The cluster name. + stream (str): + The stream name. The service will return the + events for the given stream. + receiver (str): + A name for the receiver to self-identify. + + This is used to keep track of a receiver's read + progress. + controlled_mode (google.cloud.visionai_v1alpha1.types.ControlledMode): + Controller mode configuration for receiving + events from the server. + heartbeat_interval (google.protobuf.duration_pb2.Duration): + The maximum duration of server silence before the client + determines the server unreachable. + + The client must either receive an ``Event`` update or a + heart beat message before this duration expires; otherwise, + the client will automatically cancel the current connection + and retry. + writes_done_grace_period (google.protobuf.duration_pb2.Duration): + The grace period after which a ``writes_done_request`` is + issued, that a ``WritesDone`` is expected from the client. + + The server is free to cancel the RPC should this expire. + + A system default will be chosen if unset. + """ + + cluster: str = proto.Field( + proto.STRING, + number=1, + ) + stream: str = proto.Field( + proto.STRING, + number=2, + ) + receiver: str = proto.Field( + proto.STRING, + number=3, + ) + controlled_mode: 'ControlledMode' = proto.Field( + proto.MESSAGE, + number=4, + message='ControlledMode', + ) + heartbeat_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + writes_done_grace_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + setup_request: SetupRequest = proto.Field( + proto.MESSAGE, + number=1, + oneof='request', + message=SetupRequest, + ) + commit_request: 'CommitRequest' = proto.Field( + proto.MESSAGE, + number=2, + oneof='request', + message='CommitRequest', + ) + + +class EventUpdate(proto.Message): + r"""The event update message. + + Attributes: + stream (str): + The name of the stream that the event is + attached to. + event (str): + The name of the event. + series (str): + The name of the series. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the Event update happens. + offset (int): + The offset of the message that will be used + to acknowledge of the message receiving. + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + event: str = proto.Field( + proto.STRING, + number=2, + ) + series: str = proto.Field( + proto.STRING, + number=3, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + offset: int = proto.Field( + proto.INT64, + number=5, + ) + + +class ReceiveEventsControlResponse(proto.Message): + r"""Control message for a ReceiveEventsResponse. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + heartbeat (bool): + A server heartbeat. + + This field is a member of `oneof`_ ``control``. + writes_done_request (bool): + A request to the receiver to complete any final writes + followed by a ``WritesDone``; e.g. issue any final + ``CommitRequest``\ s. + + May be ignored if ``WritesDone`` has already been issued at + any point prior to receiving this message. + + If ``WritesDone`` does not get issued, then the server will + forcefully cancel the connection, and the receiver will + likely receive an uninformative after ``Read`` returns + ``false`` and ``Finish`` is called. + + This field is a member of `oneof`_ ``control``. + """ + + heartbeat: bool = proto.Field( + proto.BOOL, + number=1, + oneof='control', + ) + writes_done_request: bool = proto.Field( + proto.BOOL, + number=2, + oneof='control', + ) + + +class ReceiveEventsResponse(proto.Message): + r"""Response message for the ReceiveEvents. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + event_update (google.cloud.visionai_v1alpha1.types.EventUpdate): + The event update message. + + This field is a member of `oneof`_ ``response``. + control (google.cloud.visionai_v1alpha1.types.ReceiveEventsControlResponse): + A control message from the server. + + This field is a member of `oneof`_ ``response``. + """ + + event_update: 'EventUpdate' = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message='EventUpdate', + ) + control: 'ReceiveEventsControlResponse' = proto.Field( + proto.MESSAGE, + number=2, + oneof='response', + message='ReceiveEventsControlResponse', + ) + + +class Lease(proto.Message): + r"""The lease message. + + Attributes: + id (str): + The lease id. + series (str): + The series name. + owner (str): + The owner name. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The lease expire time. + lease_type (google.cloud.visionai_v1alpha1.types.LeaseType): + The lease type. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + series: str = proto.Field( + proto.STRING, + number=2, + ) + owner: str = proto.Field( + proto.STRING, + number=3, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + lease_type: 'LeaseType' = proto.Field( + proto.ENUM, + number=5, + enum='LeaseType', + ) + + +class AcquireLeaseRequest(proto.Message): + r"""Request message for acquiring a lease. + + Attributes: + series (str): + The series name. + owner (str): + The owner name. + term (google.protobuf.duration_pb2.Duration): + The lease term. + lease_type (google.cloud.visionai_v1alpha1.types.LeaseType): + The lease type. + """ + + series: str = proto.Field( + proto.STRING, + number=1, + ) + owner: str = proto.Field( + proto.STRING, + number=2, + ) + term: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + lease_type: 'LeaseType' = proto.Field( + proto.ENUM, + number=4, + enum='LeaseType', + ) + + +class RenewLeaseRequest(proto.Message): + r"""Request message for renewing a lease. + + Attributes: + id (str): + Lease id. + series (str): + Series name. + owner (str): + Lease owner. + term (google.protobuf.duration_pb2.Duration): + Lease term. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + series: str = proto.Field( + proto.STRING, + number=2, + ) + owner: str = proto.Field( + proto.STRING, + number=3, + ) + term: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + + +class ReleaseLeaseRequest(proto.Message): + r"""Request message for releasing lease. + + Attributes: + id (str): + Lease id. + series (str): + Series name. + owner (str): + Lease owner. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + series: str = proto.Field( + proto.STRING, + number=2, + ) + owner: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ReleaseLeaseResponse(proto.Message): + r"""Response message for release lease. + """ + + +class RequestMetadata(proto.Message): + r"""RequestMetadata is the metadata message for the request. + + Attributes: + stream (str): + Stream name. + event (str): + Evevt name. + series (str): + Series name. + lease_id (str): + Lease id. + owner (str): + Owner name. + lease_term (google.protobuf.duration_pb2.Duration): + Lease term specifies how long the client + wants the session to be maintained by the server + after the client leaves. If the lease term is + not set, the server will release the session + immediately and the client cannot reconnect to + the same session later. + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + event: str = proto.Field( + proto.STRING, + number=2, + ) + series: str = proto.Field( + proto.STRING, + number=3, + ) + lease_id: str = proto.Field( + proto.STRING, + number=4, + ) + owner: str = proto.Field( + proto.STRING, + number=5, + ) + lease_term: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + +class SendPacketsRequest(proto.Message): + r"""Request message for sending packets. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + packet (google.cloud.visionai_v1alpha1.types.Packet): + Packets sent over the streaming rpc. + + This field is a member of `oneof`_ ``request``. + metadata (google.cloud.visionai_v1alpha1.types.RequestMetadata): + The first message of the streaming rpc + including the request metadata. + + This field is a member of `oneof`_ ``request``. + """ + + packet: streaming_resources.Packet = proto.Field( + proto.MESSAGE, + number=1, + oneof='request', + message=streaming_resources.Packet, + ) + metadata: 'RequestMetadata' = proto.Field( + proto.MESSAGE, + number=2, + oneof='request', + message='RequestMetadata', + ) + + +class SendPacketsResponse(proto.Message): + r"""Response message for sending packets. + """ + + +class ReceivePacketsRequest(proto.Message): + r"""Request message for receiving packets. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + setup_request (google.cloud.visionai_v1alpha1.types.ReceivePacketsRequest.SetupRequest): + The request to setup the initial state of + session. + The client must send and only send this as the + first message. + + This field is a member of `oneof`_ ``request``. + commit_request (google.cloud.visionai_v1alpha1.types.CommitRequest): + This request checkpoints the consumer's read + progress. + + This field is a member of `oneof`_ ``request``. + """ + + class SetupRequest(proto.Message): + r"""The message specifying the initial settings for the + ReceivePackets session. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + eager_receive_mode (google.cloud.visionai_v1alpha1.types.EagerMode): + Options for configuring eager mode. + + This field is a member of `oneof`_ ``consumer_mode``. + controlled_receive_mode (google.cloud.visionai_v1alpha1.types.ControlledMode): + Options for configuring controlled mode. + + This field is a member of `oneof`_ ``consumer_mode``. + metadata (google.cloud.visionai_v1alpha1.types.RequestMetadata): + The configurations that specify where packets + are retrieved. + receiver (str): + A name for the receiver to self-identify. + + This is used to keep track of a receiver's read + progress. + heartbeat_interval (google.protobuf.duration_pb2.Duration): + The maximum duration of server silence before the client + determines the server unreachable. + + The client must either receive a ``Packet`` or a heart beat + message before this duration expires; otherwise, the client + will automatically cancel the current connection and retry. + writes_done_grace_period (google.protobuf.duration_pb2.Duration): + The grace period after which a ``writes_done_request`` is + issued, that a ``WritesDone`` is expected from the client. + + The server is free to cancel the RPC should this expire. + + A system default will be chosen if unset. + """ + + eager_receive_mode: 'EagerMode' = proto.Field( + proto.MESSAGE, + number=3, + oneof='consumer_mode', + message='EagerMode', + ) + controlled_receive_mode: 'ControlledMode' = proto.Field( + proto.MESSAGE, + number=4, + oneof='consumer_mode', + message='ControlledMode', + ) + metadata: 'RequestMetadata' = proto.Field( + proto.MESSAGE, + number=1, + message='RequestMetadata', + ) + receiver: str = proto.Field( + proto.STRING, + number=2, + ) + heartbeat_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + writes_done_grace_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + setup_request: SetupRequest = proto.Field( + proto.MESSAGE, + number=6, + oneof='request', + message=SetupRequest, + ) + commit_request: 'CommitRequest' = proto.Field( + proto.MESSAGE, + number=7, + oneof='request', + message='CommitRequest', + ) + + +class ReceivePacketsControlResponse(proto.Message): + r"""Control message for a ReceivePacketsResponse. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + heartbeat (bool): + A server heartbeat. + + This field is a member of `oneof`_ ``control``. + writes_done_request (bool): + A request to the receiver to complete any final writes + followed by a ``WritesDone``; e.g. issue any final + ``CommitRequest``\ s. + + May be ignored if ``WritesDone`` has already been issued at + any point prior to receiving this message. + + If ``WritesDone`` does not get issued, then the server will + forcefully cancel the connection, and the receiver will + likely receive an uninformative after ``Read`` returns + ``false`` and ``Finish`` is called. + + This field is a member of `oneof`_ ``control``. + """ + + heartbeat: bool = proto.Field( + proto.BOOL, + number=1, + oneof='control', + ) + writes_done_request: bool = proto.Field( + proto.BOOL, + number=2, + oneof='control', + ) + + +class ReceivePacketsResponse(proto.Message): + r"""Response message from ReceivePackets. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + packet (google.cloud.visionai_v1alpha1.types.Packet): + A genuine data payload originating from the + sender. + + This field is a member of `oneof`_ ``response``. + control (google.cloud.visionai_v1alpha1.types.ReceivePacketsControlResponse): + A control message from the server. + + This field is a member of `oneof`_ ``response``. + """ + + packet: streaming_resources.Packet = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message=streaming_resources.Packet, + ) + control: 'ReceivePacketsControlResponse' = proto.Field( + proto.MESSAGE, + number=3, + oneof='response', + message='ReceivePacketsControlResponse', + ) + + +class EagerMode(proto.Message): + r"""The options for receiver under the eager mode. + """ + + +class ControlledMode(proto.Message): + r"""The options for receiver under the controlled mode. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + starting_logical_offset (str): + This can be set to the following logical + starting points: + "begin": This will read from the earliest + available message. + + "most-recent": This will read from the latest + available message. + + "end": This will read only future messages. + + "stored": This will resume reads one past the + last committed offset. It is the only + option that resumes progress; all others + jump unilaterally. + + This field is a member of `oneof`_ ``starting_offset``. + fallback_starting_offset (str): + This is the logical starting point to + fallback upon should the specified starting + offset be unavailable. + + This can be one of the following values: + + "begin": This will read from the earliest + available message. + + "end": This will read only future messages. + """ + + starting_logical_offset: str = proto.Field( + proto.STRING, + number=1, + oneof='starting_offset', + ) + fallback_starting_offset: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CommitRequest(proto.Message): + r"""The message for explicitly committing the read progress. + + This may only be used when ``ReceivePacketsControlledMode`` is set + in the initial setup request. + + Attributes: + offset (int): + The offset to commit. + """ + + offset: int = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streams_resources.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streams_resources.py new file mode 100644 index 000000000000..c40196bde57c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streams_resources.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'Stream', + 'Event', + 'Series', + 'Channel', + }, +) + + +class Stream(proto.Message): + r"""Message describing the Stream object. The Stream and the + Event resources are many to many; i.e., each Stream resource can + associate to many Event resources and each Event resource can + associate to many Stream resources. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + display_name (str): + The display name for the stream resource. + enable_hls_playback (bool): + Whether to enable the HLS playback service on + this stream. + media_warehouse_asset (str): + The name of the media warehouse asset for long term storage + of stream data. Format: + projects/${p_id}/locations/${l_id}/corpora/${c_id}/assets/${a_id} + Remain empty if the media warehouse storage is not needed + for the stream. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + enable_hls_playback: bool = proto.Field( + proto.BOOL, + number=7, + ) + media_warehouse_asset: str = proto.Field( + proto.STRING, + number=8, + ) + + +class Event(proto.Message): + r"""Message describing the Event object. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + alignment_clock (google.cloud.visionai_v1alpha1.types.Event.Clock): + The clock used for joining streams. + grace_period (google.protobuf.duration_pb2.Duration): + Grace period for cleaning up the event. This is the time the + controller waits for before deleting the event. During this + period, if there is any active channel on the event. The + deletion of the event after grace_period will be ignored. + """ + class Clock(proto.Enum): + r"""Clock that will be used for joining streams. + + Values: + CLOCK_UNSPECIFIED (0): + Clock is not specified. + CAPTURE (1): + Use the timestamp when the data is captured. + Clients need to sync the clock. + INGEST (2): + Use the timestamp when the data is received. + """ + CLOCK_UNSPECIFIED = 0 + CAPTURE = 1 + INGEST = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + alignment_clock: Clock = proto.Field( + proto.ENUM, + number=6, + enum=Clock, + ) + grace_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + + +class Series(proto.Message): + r"""Message describing the Series object. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + stream (str): + Required. Stream that is associated with this + series. + event (str): + Required. Event that is associated with this + series. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + stream: str = proto.Field( + proto.STRING, + number=6, + ) + event: str = proto.Field( + proto.STRING, + number=7, + ) + + +class Channel(proto.Message): + r"""Message describing the Channel object. + + Attributes: + name (str): + Name of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update timestamp. + labels (MutableMapping[str, str]): + Labels as key value pairs. + annotations (MutableMapping[str, str]): + Annotations to allow clients to store small + amounts of arbitrary data. + stream (str): + Required. Stream that is associated with this + series. + event (str): + Required. Event that is associated with this + series. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + stream: str = proto.Field( + proto.STRING, + number=6, + ) + event: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streams_service.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streams_service.py new file mode 100644 index 000000000000..e4ad8c829417 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/streams_service.py @@ -0,0 +1,1074 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'ListClustersRequest', + 'ListClustersResponse', + 'GetClusterRequest', + 'CreateClusterRequest', + 'UpdateClusterRequest', + 'DeleteClusterRequest', + 'ListStreamsRequest', + 'ListStreamsResponse', + 'GetStreamRequest', + 'CreateStreamRequest', + 'UpdateStreamRequest', + 'DeleteStreamRequest', + 'GetStreamThumbnailResponse', + 'GenerateStreamHlsTokenRequest', + 'GenerateStreamHlsTokenResponse', + 'ListEventsRequest', + 'ListEventsResponse', + 'GetEventRequest', + 'CreateEventRequest', + 'UpdateEventRequest', + 'DeleteEventRequest', + 'ListSeriesRequest', + 'ListSeriesResponse', + 'GetSeriesRequest', + 'CreateSeriesRequest', + 'UpdateSeriesRequest', + 'DeleteSeriesRequest', + 'MaterializeChannelRequest', + }, +) + + +class ListClustersRequest(proto.Message): + r"""Message for requesting list of Clusters. + + Attributes: + parent (str): + Required. Parent value for + ListClustersRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListClustersResponse(proto.Message): + r"""Message for response to listing Clusters. + + Attributes: + clusters (MutableSequence[google.cloud.visionai_v1alpha1.types.Cluster]): + The list of Cluster. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + clusters: MutableSequence[common.Cluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=common.Cluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetClusterRequest(proto.Message): + r"""Message for getting a Cluster. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateClusterRequest(proto.Message): + r"""Message for creating a Cluster. + + Attributes: + parent (str): + Required. Value for parent. + cluster_id (str): + Required. Id of the requesting object. + cluster (google.cloud.visionai_v1alpha1.types.Cluster): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: common.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=common.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateClusterRequest(proto.Message): + r"""Message for updating a Cluster. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + cluster (google.cloud.visionai_v1alpha1.types.Cluster): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + cluster: common.Cluster = proto.Field( + proto.MESSAGE, + number=2, + message=common.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteClusterRequest(proto.Message): + r"""Message for deleting a Cluster. + + Attributes: + name (str): + Required. Name of the resource + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListStreamsRequest(proto.Message): + r"""Message for requesting list of Streams. + + Attributes: + parent (str): + Required. Parent value for + ListStreamsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListStreamsResponse(proto.Message): + r"""Message for response to listing Streams. + + Attributes: + streams (MutableSequence[google.cloud.visionai_v1alpha1.types.Stream]): + The list of Stream. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + streams: MutableSequence[streams_resources.Stream] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=streams_resources.Stream, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetStreamRequest(proto.Message): + r"""Message for getting a Stream. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateStreamRequest(proto.Message): + r"""Message for creating a Stream. + + Attributes: + parent (str): + Required. Value for parent. + stream_id (str): + Required. Id of the requesting object. + stream (google.cloud.visionai_v1alpha1.types.Stream): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + stream_id: str = proto.Field( + proto.STRING, + number=2, + ) + stream: streams_resources.Stream = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Stream, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateStreamRequest(proto.Message): + r"""Message for updating a Stream. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Stream resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + stream (google.cloud.visionai_v1alpha1.types.Stream): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + stream: streams_resources.Stream = proto.Field( + proto.MESSAGE, + number=2, + message=streams_resources.Stream, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteStreamRequest(proto.Message): + r"""Message for deleting a Stream. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetStreamThumbnailResponse(proto.Message): + r"""Message for the response of GetStreamThumbnail. The empty + response message indicates the thumbnail image has been uploaded + to GCS successfully. + + """ + + +class GenerateStreamHlsTokenRequest(proto.Message): + r"""Request message for getting the auth token to access the + stream HLS contents. + + Attributes: + stream (str): + Required. The name of the stream. + """ + + stream: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateStreamHlsTokenResponse(proto.Message): + r"""Response message for GenerateStreamHlsToken. + + Attributes: + token (str): + The generated JWT token. + + The caller should insert this token to the + authorization header of the HTTP requests to get + the HLS playlist manifest and the video chunks. + eg: curl -H "Authorization: Bearer $TOKEN" + https://domain.com/test-stream.playback/master.m3u8 + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + The expiration time of the token. + """ + + token: str = proto.Field( + proto.STRING, + number=1, + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListEventsRequest(proto.Message): + r"""Message for requesting list of Events. + + Attributes: + parent (str): + Required. Parent value for ListEventsRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEventsResponse(proto.Message): + r"""Message for response to listing Events. + + Attributes: + events (MutableSequence[google.cloud.visionai_v1alpha1.types.Event]): + The list of Event. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + events: MutableSequence[streams_resources.Event] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=streams_resources.Event, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetEventRequest(proto.Message): + r"""Message for getting a Event. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEventRequest(proto.Message): + r"""Message for creating a Event. + + Attributes: + parent (str): + Required. Value for parent. + event_id (str): + Required. Id of the requesting object. + event (google.cloud.visionai_v1alpha1.types.Event): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_id: str = proto.Field( + proto.STRING, + number=2, + ) + event: streams_resources.Event = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Event, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateEventRequest(proto.Message): + r"""Message for updating a Event. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Event resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + event (google.cloud.visionai_v1alpha1.types.Event): + Required. The resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + event: streams_resources.Event = proto.Field( + proto.MESSAGE, + number=2, + message=streams_resources.Event, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteEventRequest(proto.Message): + r"""Message for deleting a Event. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSeriesRequest(proto.Message): + r"""Message for requesting list of Series. + + Attributes: + parent (str): + Required. Parent value for ListSeriesRequest. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results. + order_by (str): + Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSeriesResponse(proto.Message): + r"""Message for response to listing Series. + + Attributes: + series (MutableSequence[google.cloud.visionai_v1alpha1.types.Series]): + The list of Series. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + series: MutableSequence[streams_resources.Series] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=streams_resources.Series, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetSeriesRequest(proto.Message): + r"""Message for getting a Series. + + Attributes: + name (str): + Required. Name of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSeriesRequest(proto.Message): + r"""Message for creating a Series. + + Attributes: + parent (str): + Required. Value for parent. + series_id (str): + Required. Id of the requesting object. + series (google.cloud.visionai_v1alpha1.types.Series): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + series_id: str = proto.Field( + proto.STRING, + number=2, + ) + series: streams_resources.Series = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Series, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateSeriesRequest(proto.Message): + r"""Message for updating a Series. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Series resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + series (google.cloud.visionai_v1alpha1.types.Series): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + series: streams_resources.Series = proto.Field( + proto.MESSAGE, + number=2, + message=streams_resources.Series, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteSeriesRequest(proto.Message): + r"""Message for deleting a Series. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MaterializeChannelRequest(proto.Message): + r"""Message for materializing a channel. + + Attributes: + parent (str): + Required. Value for parent. + channel_id (str): + Required. Id of the channel. + channel (google.cloud.visionai_v1alpha1.types.Channel): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + channel_id: str = proto.Field( + proto.STRING, + number=2, + ) + channel: streams_resources.Channel = proto.Field( + proto.MESSAGE, + number=3, + message=streams_resources.Channel, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/warehouse.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/warehouse.py new file mode 100644 index 000000000000..e83da5a26b49 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/google/cloud/visionai_v1alpha1/types/warehouse.py @@ -0,0 +1,2557 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.visionai.v1alpha1', + manifest={ + 'FacetBucketType', + 'CreateAssetRequest', + 'GetAssetRequest', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'UpdateAssetRequest', + 'DeleteAssetRequest', + 'Asset', + 'CreateCorpusRequest', + 'CreateCorpusMetadata', + 'Corpus', + 'GetCorpusRequest', + 'UpdateCorpusRequest', + 'ListCorporaRequest', + 'ListCorporaResponse', + 'DeleteCorpusRequest', + 'CreateDataSchemaRequest', + 'DataSchema', + 'DataSchemaDetails', + 'UpdateDataSchemaRequest', + 'GetDataSchemaRequest', + 'DeleteDataSchemaRequest', + 'ListDataSchemasRequest', + 'ListDataSchemasResponse', + 'CreateAnnotationRequest', + 'Annotation', + 'UserSpecifiedAnnotation', + 'GeoCoordinate', + 'AnnotationValue', + 'ListAnnotationsRequest', + 'ListAnnotationsResponse', + 'GetAnnotationRequest', + 'UpdateAnnotationRequest', + 'DeleteAnnotationRequest', + 'CreateSearchConfigRequest', + 'UpdateSearchConfigRequest', + 'GetSearchConfigRequest', + 'DeleteSearchConfigRequest', + 'ListSearchConfigsRequest', + 'ListSearchConfigsResponse', + 'SearchConfig', + 'FacetProperty', + 'SearchCriteriaProperty', + 'FacetValue', + 'FacetBucket', + 'FacetGroup', + 'IngestAssetRequest', + 'IngestAssetResponse', + 'ClipAssetRequest', + 'ClipAssetResponse', + 'GenerateHlsUriRequest', + 'GenerateHlsUriResponse', + 'SearchAssetsRequest', + 'DeleteAssetMetadata', + 'AnnotationMatchingResult', + 'SearchResultItem', + 'SearchAssetsResponse', + 'IntRange', + 'FloatRange', + 'StringArray', + 'IntRangeArray', + 'FloatRangeArray', + 'DateTimeRange', + 'DateTimeRangeArray', + 'CircleArea', + 'GeoLocationArray', + 'BoolValue', + 'Criteria', + 'Partition', + }, +) + + +class FacetBucketType(proto.Enum): + r"""Different types for a facet bucket. + + Values: + FACET_BUCKET_TYPE_UNSPECIFIED (0): + Unspecified type. + FACET_BUCKET_TYPE_VALUE (1): + Value type. + FACET_BUCKET_TYPE_DATETIME (2): + Datetime type. + FACET_BUCKET_TYPE_FIXED_RANGE (3): + Fixed Range type. + FACET_BUCKET_TYPE_CUSTOM_RANGE (4): + Custom Range type. + """ + FACET_BUCKET_TYPE_UNSPECIFIED = 0 + FACET_BUCKET_TYPE_VALUE = 1 + FACET_BUCKET_TYPE_DATETIME = 2 + FACET_BUCKET_TYPE_FIXED_RANGE = 3 + FACET_BUCKET_TYPE_CUSTOM_RANGE = 4 + + +class CreateAssetRequest(proto.Message): + r"""Request message for CreateAssetRequest. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource where this asset will be + created. Format: projects/\ */locations/*/corpora/\* + asset (google.cloud.visionai_v1alpha1.types.Asset): + Required. The asset to create. + asset_id (str): + Optional. The ID to use for the asset, which will become the + final component of the asset's resource name if user choose + to specify. Otherwise, asset id will be generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must be a + letter, the last could be a letter or a number. + + This field is a member of `oneof`_ ``_asset_id``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + asset: 'Asset' = proto.Field( + proto.MESSAGE, + number=2, + message='Asset', + ) + asset_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class GetAssetRequest(proto.Message): + r"""Request message for GetAsset. + + Attributes: + name (str): + Required. The name of the asset to retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for ListAssets. + + Attributes: + parent (str): + Required. The parent, which owns this collection of assets. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus} + page_size (int): + The maximum number of assets to return. The + service may return fewer than this value. + If unspecified, at most 50 assets will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListAssets`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListAssets`` must match the call that provided the page + token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for ListAssets. + + Attributes: + assets (MutableSequence[google.cloud.visionai_v1alpha1.types.Asset]): + The assets from the specified corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + assets: MutableSequence['Asset'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Asset', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateAssetRequest(proto.Message): + r"""Response message for UpdateAsset. + + Attributes: + asset (google.cloud.visionai_v1alpha1.types.Asset): + Required. The asset to update. + + The asset's ``name`` field is used to identify the asset to + be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + asset: 'Asset' = proto.Field( + proto.MESSAGE, + number=1, + message='Asset', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAssetRequest(proto.Message): + r"""Request message for DeleteAsset. + + Attributes: + name (str): + Required. The name of the asset to delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Asset(proto.Message): + r"""An asset is a resource in corpus. It represents a media + object inside corpus, contains metadata and another resource + annotation. Different feature could be applied to the asset to + generate annotations. User could specified annotation related to + the target asset. + + Attributes: + name (str): + Resource name of the asset. Form: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}`` + ttl (google.protobuf.duration_pb2.Duration): + The duration for which all media assets, + associated metadata, and search documents can + exist. If not set, then it will using the + default ttl in the parent corpus resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class CreateCorpusRequest(proto.Message): + r"""Request message of CreateCorpus API. + + Attributes: + parent (str): + Required. Form: + ``projects/{project_number}/locations/{location_id}`` + corpus (google.cloud.visionai_v1alpha1.types.Corpus): + Required. The corpus to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + corpus: 'Corpus' = proto.Field( + proto.MESSAGE, + number=2, + message='Corpus', + ) + + +class CreateCorpusMetadata(proto.Message): + r"""Metadata for CreateCorpus API. + """ + + +class Corpus(proto.Message): + r"""Corpus is a set of video contents for management. Within a + corpus, videos share the same data schema. Search is also + restricted within a single corpus. + + Attributes: + name (str): + Resource name of the corpus. Form: + ``projects/{project_number}/locations/{location_id}/corpora/{corpus_id}`` + display_name (str): + Required. The corpus name to shown in the UI. + The name can be up to 32 characters long. + description (str): + Optional. Description of the corpus. Can be + up to 25000 characters long. + default_ttl (google.protobuf.duration_pb2.Duration): + Required. The default TTL value for all + assets under the corpus without a asset level + user-defined TTL with a maximum of 10 years. + This is required for all corpora. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + default_ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + +class GetCorpusRequest(proto.Message): + r"""Request message for GetCorpus. + + Attributes: + name (str): + Required. The resource name of the corpus to + retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCorpusRequest(proto.Message): + r"""Request message for UpdateCorpus. + + Attributes: + corpus (google.cloud.visionai_v1alpha1.types.Corpus): + Required. The corpus which replaces the + resource on the server. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + corpus: 'Corpus' = proto.Field( + proto.MESSAGE, + number=1, + message='Corpus', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListCorporaRequest(proto.Message): + r"""Request message for ListCorpora. + + Attributes: + parent (str): + Required. The resource name of the project + from which to list corpora. + page_size (int): + Requested page size. API may return fewer results than + requested. If negative, INVALID_ARGUMENT error will be + returned. If unspecified or 0, API will pick a default size, + which is 10. If the requested page size is larger than the + maximum size, API will pick use the maximum size, which is + 20. + page_token (str): + A token identifying a page of results for the server to + return. Typically obtained via + [ListCorpora.next_page_token][] of the previous + [Warehouse.ListCorpora][google.cloud.visionai.v1alpha1.Warehouse.ListCorpora] + call. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCorporaResponse(proto.Message): + r"""Response message for ListCorpora. + + Attributes: + corpora (MutableSequence[google.cloud.visionai_v1alpha1.types.Corpus]): + The corpora in the project. + next_page_token (str): + A token to retrieve next page of results. Pass to + [ListCorporaRequest.page_token][google.cloud.visionai.v1alpha1.ListCorporaRequest.page_token] + to obtain that page. + """ + + @property + def raw_page(self): + return self + + corpora: MutableSequence['Corpus'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Corpus', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteCorpusRequest(proto.Message): + r"""Request message for DeleteCorpus. + + Attributes: + name (str): + Required. The resource name of the corpus to + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDataSchemaRequest(proto.Message): + r"""Request message for CreateDataSchema. + + Attributes: + parent (str): + Required. The parent resource where this data schema will be + created. Format: projects/\ */locations/*/corpora/\* + data_schema (google.cloud.visionai_v1alpha1.types.DataSchema): + Required. The data schema to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_schema: 'DataSchema' = proto.Field( + proto.MESSAGE, + number=2, + message='DataSchema', + ) + + +class DataSchema(proto.Message): + r"""Data schema indicates how the user specified annotation is + interpreted in the system. + + Attributes: + name (str): + Resource name of the data schema in the form of: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`` + where {data_schema} part should be the same as the ``key`` + field below. + key (str): + Required. The key of this data schema. This key should be + matching the key of user specified annotation and unique + inside corpus. This value can be up to 63 characters, and + valid characters are /[a-z][0-9]-/. The first character must + be a letter, the last could be a letter or a number. + schema_details (google.cloud.visionai_v1alpha1.types.DataSchemaDetails): + The schema details mapping to the key. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + key: str = proto.Field( + proto.STRING, + number=2, + ) + schema_details: 'DataSchemaDetails' = proto.Field( + proto.MESSAGE, + number=3, + message='DataSchemaDetails', + ) + + +class DataSchemaDetails(proto.Message): + r"""Data schema details indicates the data type and the data + struct corresponding to the key of user specified annotation. + + Attributes: + type_ (google.cloud.visionai_v1alpha1.types.DataSchemaDetails.DataType): + Type of the annotation. + proto_any_config (google.cloud.visionai_v1alpha1.types.DataSchemaDetails.ProtoAnyConfig): + Config for protobuf any type. + granularity (google.cloud.visionai_v1alpha1.types.DataSchemaDetails.Granularity): + The granularity associated with this + DataSchema. + search_strategy (google.cloud.visionai_v1alpha1.types.DataSchemaDetails.SearchStrategy): + The search strategy to be applied on the ``key`` above. + """ + class DataType(proto.Enum): + r"""Data type of the annotation. + + Values: + DATA_TYPE_UNSPECIFIED (0): + Unspecified type. + INTEGER (1): + Integer type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + IntRangeArray. + FLOAT (2): + Float type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + FloatRangeArray. + STRING (3): + String type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH, + - DataSchema.SearchStrategy.SMART_SEARCH. + DATETIME (5): + Supported formats: %Y-%m-%dT%H:%M:%E\ *S%E*\ z + (absl::RFC3339_full) %Y-%m-%dT%H:%M:%E\ *S + %Y-%m-%dT%H:%M%E*\ z %Y-%m-%dT%H:%M %Y-%m-%dT%H%E\ *z + %Y-%m-%dT%H %Y-%m-%d%E*\ z %Y-%m-%d %Y-%m %Y Allowed search + strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + DateTimeRangeArray. + GEO_COORDINATE (7): + Geo coordinate type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. Supports query by + GeoLocationArray. + PROTO_ANY (8): + Type to pass any proto as available in annotations.proto. + Only use internally. Available proto types and its + corresponding search behavior: + + - ImageObjectDetectionPredictionResult, allows SMART_SEARCH + on display_names and NO_SEARCH. + - ClassificationPredictionResult, allows SMART_SEARCH on + display_names and NO_SEARCH. + - ImageSegmentationPredictionResult, allows NO_SEARCH. + - VideoActionRecognitionPredictionResult, allows + SMART_SEARCH on display_name and NO_SEARCH. + - VideoObjectTrackingPredictionResult, allows SMART_SEARCH + on display_name and NO_SEARCH. + - VideoClassificationPredictionResult, allows SMART_SEARCH + on display_name and NO_SEARCH. + - OccupancyCountingPredictionResult, allows EXACT_SEARCH on + stats.full_frame_count.count and NO_SEARCH. + - ObjectDetectionPredictionResult, allows SMART_SEARCH on + identified_boxes.entity.label_string and NO_SEARCH. + BOOLEAN (9): + Boolean type. Allowed search strategies: + + - DataSchema.SearchStrategy.NO_SEARCH, + - DataSchema.SearchStrategy.EXACT_SEARCH. + """ + DATA_TYPE_UNSPECIFIED = 0 + INTEGER = 1 + FLOAT = 2 + STRING = 3 + DATETIME = 5 + GEO_COORDINATE = 7 + PROTO_ANY = 8 + BOOLEAN = 9 + + class Granularity(proto.Enum): + r"""The granularity of annotations under this DataSchema. + + Values: + GRANULARITY_UNSPECIFIED (0): + Unspecified granularity. + GRANULARITY_ASSET_LEVEL (1): + Asset-level granularity (annotations must not + contain partition info). + GRANULARITY_PARTITION_LEVEL (2): + Partition-level granularity (annotations must + contain partition info). + """ + GRANULARITY_UNSPECIFIED = 0 + GRANULARITY_ASSET_LEVEL = 1 + GRANULARITY_PARTITION_LEVEL = 2 + + class ProtoAnyConfig(proto.Message): + r"""The configuration for ``PROTO_ANY`` data type. + + Attributes: + type_uri (str): + The type URI of the proto message. + """ + + type_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class SearchStrategy(proto.Message): + r"""The search strategy for annotations value of the ``key``. + + Attributes: + search_strategy_type (google.cloud.visionai_v1alpha1.types.DataSchemaDetails.SearchStrategy.SearchStrategyType): + The type of search strategy to be applied on the ``key`` + above. The allowed ``search_strategy_type`` is different for + different data types, which is documented in the + DataSchemaDetails.DataType. Specifying unsupported + ``search_strategy_type`` for data types will result in + INVALID_ARGUMENT error. + """ + class SearchStrategyType(proto.Enum): + r"""The types of search strategies to be applied on the + annotation key. + + Values: + NO_SEARCH (0): + Annotatation values of the ``key`` above will not be + searchable. + EXACT_SEARCH (1): + When searching with ``key``, the value must be exactly as + the annotation value that has been ingested. + SMART_SEARCH (2): + When searching with ``key``, Warehouse will perform broad + search based on semantic of the annotation value. + """ + NO_SEARCH = 0 + EXACT_SEARCH = 1 + SMART_SEARCH = 2 + + search_strategy_type: 'DataSchemaDetails.SearchStrategy.SearchStrategyType' = proto.Field( + proto.ENUM, + number=1, + enum='DataSchemaDetails.SearchStrategy.SearchStrategyType', + ) + + type_: DataType = proto.Field( + proto.ENUM, + number=1, + enum=DataType, + ) + proto_any_config: ProtoAnyConfig = proto.Field( + proto.MESSAGE, + number=6, + message=ProtoAnyConfig, + ) + granularity: Granularity = proto.Field( + proto.ENUM, + number=5, + enum=Granularity, + ) + search_strategy: SearchStrategy = proto.Field( + proto.MESSAGE, + number=7, + message=SearchStrategy, + ) + + +class UpdateDataSchemaRequest(proto.Message): + r"""Request message for UpdateDataSchema. + + Attributes: + data_schema (google.cloud.visionai_v1alpha1.types.DataSchema): + Required. The data schema's ``name`` field is used to + identify the data schema to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + data_schema: 'DataSchema' = proto.Field( + proto.MESSAGE, + number=1, + message='DataSchema', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetDataSchemaRequest(proto.Message): + r"""Request message for GetDataSchema. + + Attributes: + name (str): + Required. The name of the data schema to retrieve. Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteDataSchemaRequest(proto.Message): + r"""Request message for DeleteDataSchema. + + Attributes: + name (str): + Required. The name of the data schema to delete. Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/dataSchemas/{data_schema_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDataSchemasRequest(proto.Message): + r"""Request message for ListDataSchemas. + + Attributes: + parent (str): + Required. The parent, which owns this collection of data + schemas. Format: + projects/{project_number}/locations/{location_id}/corpora/{corpus_id} + page_size (int): + The maximum number of data schemas to return. + The service may return fewer than this value. If + unspecified, at most 50 data schemas will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListDataSchemas`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDataSchemas`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDataSchemasResponse(proto.Message): + r"""Response message for ListDataSchemas. + + Attributes: + data_schemas (MutableSequence[google.cloud.visionai_v1alpha1.types.DataSchema]): + The data schemas from the specified corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + data_schemas: MutableSequence['DataSchema'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DataSchema', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAnnotationRequest(proto.Message): + r"""Request message for CreateAnnotation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent resource where this annotation will be + created. Format: projects/\ */locations/*/corpora/*/assets/* + annotation (google.cloud.visionai_v1alpha1.types.Annotation): + Required. The annotation to create. + annotation_id (str): + Optional. The ID to use for the annotation, which will + become the final component of the annotation's resource name + if user choose to specify. Otherwise, annotation id will be + generated by system. + + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-/. The first character must be a + letter, the last could be a letter or a number. + + This field is a member of `oneof`_ ``_annotation_id``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + annotation: 'Annotation' = proto.Field( + proto.MESSAGE, + number=2, + message='Annotation', + ) + annotation_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class Annotation(proto.Message): + r"""An annotation is a resource in asset. It represents a + key-value mapping of content in asset. + + Attributes: + name (str): + Resource name of the annotation. Form: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}`` + user_specified_annotation (google.cloud.visionai_v1alpha1.types.UserSpecifiedAnnotation): + User provided annotation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + user_specified_annotation: 'UserSpecifiedAnnotation' = proto.Field( + proto.MESSAGE, + number=2, + message='UserSpecifiedAnnotation', + ) + + +class UserSpecifiedAnnotation(proto.Message): + r"""Annotation provided by users. + + Attributes: + key (str): + Required. Key of the annotation. The key must + be set with type by CreateDataSchema. + value (google.cloud.visionai_v1alpha1.types.AnnotationValue): + Value of the annotation. The value must be + able to convert to the type according to the + data schema. + partition (google.cloud.visionai_v1alpha1.types.Partition): + Partition information in time and space for + the sub-asset level annotation. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: 'AnnotationValue' = proto.Field( + proto.MESSAGE, + number=2, + message='AnnotationValue', + ) + partition: 'Partition' = proto.Field( + proto.MESSAGE, + number=3, + message='Partition', + ) + + +class GeoCoordinate(proto.Message): + r"""Location Coordinate Representation + + Attributes: + latitude (float): + Latitude Coordinate. Degrees [-90 .. 90] + longitude (float): + Longitude Coordinate. Degrees [-180 .. 180] + """ + + latitude: float = proto.Field( + proto.DOUBLE, + number=1, + ) + longitude: float = proto.Field( + proto.DOUBLE, + number=2, + ) + + +class AnnotationValue(proto.Message): + r"""Value of annotation, including all types available in data + schema. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + int_value (int): + Value of int type annotation. + + This field is a member of `oneof`_ ``value``. + float_value (float): + Value of float type annotation. + + This field is a member of `oneof`_ ``value``. + str_value (str): + Value of string type annotation. + + This field is a member of `oneof`_ ``value``. + datetime_value (str): + Value of date time type annotation. + + This field is a member of `oneof`_ ``value``. + geo_coordinate (google.cloud.visionai_v1alpha1.types.GeoCoordinate): + Value of geo coordinate type annotation. + + This field is a member of `oneof`_ ``value``. + proto_any_value (google.protobuf.any_pb2.Any): + Value of any proto value. + + This field is a member of `oneof`_ ``value``. + bool_value (bool): + Value of boolean type annotation. + + This field is a member of `oneof`_ ``value``. + customized_struct_data_value (google.protobuf.struct_pb2.Struct): + Value of customized struct annotation. + + This field is a member of `oneof`_ ``value``. + """ + + int_value: int = proto.Field( + proto.INT64, + number=1, + oneof='value', + ) + float_value: float = proto.Field( + proto.FLOAT, + number=2, + oneof='value', + ) + str_value: str = proto.Field( + proto.STRING, + number=3, + oneof='value', + ) + datetime_value: str = proto.Field( + proto.STRING, + number=5, + oneof='value', + ) + geo_coordinate: 'GeoCoordinate' = proto.Field( + proto.MESSAGE, + number=7, + oneof='value', + message='GeoCoordinate', + ) + proto_any_value: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=8, + oneof='value', + message=any_pb2.Any, + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=9, + oneof='value', + ) + customized_struct_data_value: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=10, + oneof='value', + message=struct_pb2.Struct, + ) + + +class ListAnnotationsRequest(proto.Message): + r"""Request message for GetAnnotation API. + + Attributes: + parent (str): + The parent, which owns this collection of annotations. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset} + page_size (int): + The maximum number of annotations to return. + The service may return fewer than this value. If + unspecified, at most 50 annotations will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListAnnotations`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListAnnotations`` must match the call that provided the + page token. + filter (str): + The filter applied to the returned list. We only support + filtering for the following fields: + ``partition.temporal_partition.start_time``, + ``partition.temporal_partition.end_time``, and ``key``. + Timestamps are specified in the RFC-3339 format, and only + one restriction may be applied per field, joined by + conjunctions. Format: + "partition.temporal_partition.start_time > + "2012-04-21T11:30:00-04:00" AND + partition.temporal_partition.end_time < + "2012-04-22T11:30:00-04:00" AND key = "example_key"". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnnotationsResponse(proto.Message): + r"""Request message for ListAnnotations API. + + Attributes: + annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.Annotation]): + The annotations from the specified asset. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + annotations: MutableSequence['Annotation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Annotation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAnnotationRequest(proto.Message): + r"""Request message for GetAnnotation API. + + Attributes: + name (str): + Required. The name of the annotation to retrieve. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAnnotationRequest(proto.Message): + r"""Request message for UpdateAnnotation API. + + Attributes: + annotation (google.cloud.visionai_v1alpha1.types.Annotation): + Required. The annotation to update. The annotation's + ``name`` field is used to identify the annotation to be + updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + annotation: 'Annotation' = proto.Field( + proto.MESSAGE, + number=1, + message='Annotation', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAnnotationRequest(proto.Message): + r"""Request message for DeleteAnnotation API. + + Attributes: + name (str): + Required. The name of the annotation to delete. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSearchConfigRequest(proto.Message): + r"""Request message for CreateSearchConfig. + + Attributes: + parent (str): + Required. The parent resource where this search + configuration will be created. Format: + projects/\ */locations/*/corpora/\* + search_config (google.cloud.visionai_v1alpha1.types.SearchConfig): + Required. The search config to create. + search_config_id (str): + Required. ID to use for the new search config. Will become + the final component of the SearchConfig's resource name. + This value should be up to 63 characters, and valid + characters are /[a-z][0-9]-_/. The first character must be a + letter, the last could be a letter or a number. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + search_config: 'SearchConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='SearchConfig', + ) + search_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSearchConfigRequest(proto.Message): + r"""Request message for UpdateSearchConfig. + + Attributes: + search_config (google.cloud.visionai_v1alpha1.types.SearchConfig): + Required. The search configuration to update. + + The search configuration's ``name`` field is used to + identify the resource to be updated. Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If left + unset, all field paths will be + updated/overwritten. + """ + + search_config: 'SearchConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchConfig', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetSearchConfigRequest(proto.Message): + r"""Request message for GetSearchConfig. + + Attributes: + name (str): + Required. The name of the search configuration to retrieve. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteSearchConfigRequest(proto.Message): + r"""Request message for DeleteSearchConfig. + + Attributes: + name (str): + Required. The name of the search configuration to delete. + Format: + projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSearchConfigsRequest(proto.Message): + r"""Request message for ListSearchConfigs. + + Attributes: + parent (str): + Required. The parent, which owns this collection of search + configurations. Format: + projects/{project_number}/locations/{location}/corpora/{corpus} + page_size (int): + The maximum number of search configurations + to return. The service may return fewer than + this value. If unspecified, a page size of 50 + will be used. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListSearchConfigs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListSearchConfigs`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSearchConfigsResponse(proto.Message): + r"""Response message for ListSearchConfigs. + + Attributes: + search_configs (MutableSequence[google.cloud.visionai_v1alpha1.types.SearchConfig]): + The search configurations from the specified + corpus. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + search_configs: MutableSequence['SearchConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchConfig(proto.Message): + r"""SearchConfig stores different properties that will affect + search behaviors and search results. + + Attributes: + name (str): + Resource name of the search configuration. For + CustomSearchCriteria, search_config would be the search + operator name. For Facets, search_config would be the facet + dimension name. Form: + ``projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}`` + facet_property (google.cloud.visionai_v1alpha1.types.FacetProperty): + Establishes a FacetDimension and associated + specifications. + search_criteria_property (google.cloud.visionai_v1alpha1.types.SearchCriteriaProperty): + Creates a mapping between a custom + SearchCriteria and one or more UGA keys. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + facet_property: 'FacetProperty' = proto.Field( + proto.MESSAGE, + number=2, + message='FacetProperty', + ) + search_criteria_property: 'SearchCriteriaProperty' = proto.Field( + proto.MESSAGE, + number=3, + message='SearchCriteriaProperty', + ) + + +class FacetProperty(proto.Message): + r"""Central configuration for a facet. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + fixed_range_bucket_spec (google.cloud.visionai_v1alpha1.types.FacetProperty.FixedRangeBucketSpec): + Fixed range facet bucket config. + + This field is a member of `oneof`_ ``range_facet_config``. + custom_range_bucket_spec (google.cloud.visionai_v1alpha1.types.FacetProperty.CustomRangeBucketSpec): + Custom range facet bucket config. + + This field is a member of `oneof`_ ``range_facet_config``. + datetime_bucket_spec (google.cloud.visionai_v1alpha1.types.FacetProperty.DateTimeBucketSpec): + Datetime range facet bucket config. + + This field is a member of `oneof`_ ``range_facet_config``. + mapped_fields (MutableSequence[str]): + Name of the facets, which are the dimensions users want to + use to refine search results. ``mapped_fields`` will match + UserSpecifiedDataSchema keys. + + For example, user can add a bunch of UGAs with the same key, + such as player:adam, player:bob, player:charles. When + multiple mapped_fields are specified, will merge their value + together as final facet value. E.g. home_team: a, + home_team:b, away_team:a, away_team:c, when facet_field = + [home_team, away_team], facet_value will be [a, b, c]. + + UNLESS this is a 1:1 facet dimension (mapped_fields.size() + == 1) AND the mapped_field equals the parent + SearchConfig.name, the parent must also contain a + SearchCriteriaProperty that maps to the same fields. + mapped_fields must not be empty. + display_name (str): + Display name of the facet. To be used by UI + for facet rendering. + result_size (int): + Maximum number of unique bucket to return for one facet. + Bucket number can be large for high-cardinality facet such + as "player". We only return top-n most related ones to user. + If it's <= 0, the server will decide the appropriate + result_size. + bucket_type (google.cloud.visionai_v1alpha1.types.FacetBucketType): + Facet bucket type e.g. value, range. + """ + + class FixedRangeBucketSpec(proto.Message): + r"""If bucket type is FIXED_RANGE, specify how values are bucketized. + Use FixedRangeBucketSpec when you want to create multiple buckets + with equal granularities. Using integer bucket value as an example, + when bucket_start = 0, bucket_granularity = 10, bucket_count = 5, + this facet will be aggregated via the following buckets: [-inf, 0), + [0, 10), [10, 20), [20, 30), [30, inf). Notably, bucket_count <= 1 + is an invalid spec. + + Attributes: + bucket_start (google.cloud.visionai_v1alpha1.types.FacetValue): + Lower bound of the bucket. NOTE: Only integer + type is currently supported for this field. + bucket_granularity (google.cloud.visionai_v1alpha1.types.FacetValue): + Bucket granularity. NOTE: Only integer type + is currently supported for this field. + bucket_count (int): + Total number of buckets. + """ + + bucket_start: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=1, + message='FacetValue', + ) + bucket_granularity: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=2, + message='FacetValue', + ) + bucket_count: int = proto.Field( + proto.INT32, + number=3, + ) + + class CustomRangeBucketSpec(proto.Message): + r"""If bucket type is CUSTOM_RANGE, specify how values are bucketized. + Use integer bucket value as an example, when the endpoints are 0, + 10, 100, and 1000, we will generate the following facets: [-inf, 0), + [0, 10), [10, 100), [100, 1000), [1000, inf). Notably: + + - endpoints must be listed in ascending order. Otherwise, the + SearchConfig API will reject the facet config. + - < 1 endpoints is an invalid spec. + + Attributes: + endpoints (MutableSequence[google.cloud.visionai_v1alpha1.types.FacetValue]): + Currently, only integer type is supported for + this field. + """ + + endpoints: MutableSequence['FacetValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FacetValue', + ) + + class DateTimeBucketSpec(proto.Message): + r"""If bucket type is DATE, specify how date values are + bucketized. + + Attributes: + granularity (google.cloud.visionai_v1alpha1.types.FacetProperty.DateTimeBucketSpec.Granularity): + Granularity of date type facet. + """ + class Granularity(proto.Enum): + r"""Granularity enum for the datetime bucket. + + Values: + GRANULARITY_UNSPECIFIED (0): + Unspecified granularity. + YEAR (1): + Granularity is year. + MONTH (2): + Granularity is month. + DAY (3): + Granularity is day. + """ + GRANULARITY_UNSPECIFIED = 0 + YEAR = 1 + MONTH = 2 + DAY = 3 + + granularity: 'FacetProperty.DateTimeBucketSpec.Granularity' = proto.Field( + proto.ENUM, + number=1, + enum='FacetProperty.DateTimeBucketSpec.Granularity', + ) + + fixed_range_bucket_spec: FixedRangeBucketSpec = proto.Field( + proto.MESSAGE, + number=5, + oneof='range_facet_config', + message=FixedRangeBucketSpec, + ) + custom_range_bucket_spec: CustomRangeBucketSpec = proto.Field( + proto.MESSAGE, + number=6, + oneof='range_facet_config', + message=CustomRangeBucketSpec, + ) + datetime_bucket_spec: DateTimeBucketSpec = proto.Field( + proto.MESSAGE, + number=7, + oneof='range_facet_config', + message=DateTimeBucketSpec, + ) + mapped_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + result_size: int = proto.Field( + proto.INT64, + number=3, + ) + bucket_type: 'FacetBucketType' = proto.Field( + proto.ENUM, + number=4, + enum='FacetBucketType', + ) + + +class SearchCriteriaProperty(proto.Message): + r"""Central configuration for custom search criteria. + + Attributes: + mapped_fields (MutableSequence[str]): + Each mapped_field corresponds to a UGA key. To understand + how this property works, take the following example. In the + SearchConfig table, the user adds this entry: search_config + { name: "person" search_criteria_property { mapped_fields: + "player" mapped_fields: "coach" } } + + Now, when a user issues a query like: criteria { field: + "person" text_array { txt_values: "Tom Brady" txt_values: + "Bill Belichick" } } + + MWH search will return search documents where (player=Tom + Brady \|\| coach=Tom Brady \|\| player=Bill Belichick \|\| + coach=Bill Belichick). + """ + + mapped_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class FacetValue(proto.Message): + r"""Definition of a single value with generic type. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_value (str): + String type value. + + This field is a member of `oneof`_ ``value``. + integer_value (int): + Integer type value. + + This field is a member of `oneof`_ ``value``. + datetime_value (google.type.datetime_pb2.DateTime): + Datetime type value. + + This field is a member of `oneof`_ ``value``. + """ + + string_value: str = proto.Field( + proto.STRING, + number=1, + oneof='value', + ) + integer_value: int = proto.Field( + proto.INT64, + number=2, + oneof='value', + ) + datetime_value: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=3, + oneof='value', + message=datetime_pb2.DateTime, + ) + + +class FacetBucket(proto.Message): + r"""Holds the facet value, selections state, and metadata. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (google.cloud.visionai_v1alpha1.types.FacetValue): + Singular value. + + This field is a member of `oneof`_ ``bucket_value``. + range_ (google.cloud.visionai_v1alpha1.types.FacetBucket.Range): + Range value. + + This field is a member of `oneof`_ ``bucket_value``. + selected (bool): + Whether one facet bucket is selected. This + field represents user's facet selection. It is + set by frontend in SearchVideosRequest. + """ + + class Range(proto.Message): + r"""The range of values [start, end) for which faceting is applied. + + Attributes: + start (google.cloud.visionai_v1alpha1.types.FacetValue): + Start of the range. Non-existence indicates + some bound (e.g. -inf). + end (google.cloud.visionai_v1alpha1.types.FacetValue): + End of the range. Non-existence indicates + some bound (e.g. inf). + """ + + start: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=1, + message='FacetValue', + ) + end: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=2, + message='FacetValue', + ) + + value: 'FacetValue' = proto.Field( + proto.MESSAGE, + number=2, + oneof='bucket_value', + message='FacetValue', + ) + range_: Range = proto.Field( + proto.MESSAGE, + number=4, + oneof='bucket_value', + message=Range, + ) + selected: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class FacetGroup(proto.Message): + r"""A group of facet buckets to be passed back and forth between + backend & frontend. + + Attributes: + facet_id (str): + Unique id of the facet group. + display_name (str): + Display name of the facet. To be used by UI + for facet rendering. + buckets (MutableSequence[google.cloud.visionai_v1alpha1.types.FacetBucket]): + Buckets associated with the facet. E.g. for + "Team" facet, the bucket can be 49ers, patriots, + etc. + bucket_type (google.cloud.visionai_v1alpha1.types.FacetBucketType): + Facet bucket type. + fetch_matched_annotations (bool): + If true, return query matched annotations for this facet + group's selection. This option is only applicable for facets + based on partition level annotations. It supports the + following facet values: + + - INTEGER + - STRING (DataSchema.SearchStrategy.EXACT_SEARCH only) + """ + + facet_id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + buckets: MutableSequence['FacetBucket'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='FacetBucket', + ) + bucket_type: 'FacetBucketType' = proto.Field( + proto.ENUM, + number=4, + enum='FacetBucketType', + ) + fetch_matched_annotations: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class IngestAssetRequest(proto.Message): + r"""Request message for IngestAsset API. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + config (google.cloud.visionai_v1alpha1.types.IngestAssetRequest.Config): + Provides information for the data and the asset resource + name that the data belongs to. The first + ``IngestAssetRequest`` message must only contain a + ``Config`` message. + + This field is a member of `oneof`_ ``streaming_request``. + time_indexed_data (google.cloud.visionai_v1alpha1.types.IngestAssetRequest.TimeIndexedData): + Data to be ingested. + + This field is a member of `oneof`_ ``streaming_request``. + """ + + class Config(proto.Message): + r"""Configuration for the data. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + video_type (google.cloud.visionai_v1alpha1.types.IngestAssetRequest.Config.VideoType): + Type information for video data. + + This field is a member of `oneof`_ ``data_type``. + asset (str): + Required. The resource name of the asset that + the ingested data belongs to. + """ + + class VideoType(proto.Message): + r"""Type information for video data. + + Attributes: + container_format (google.cloud.visionai_v1alpha1.types.IngestAssetRequest.Config.VideoType.ContainerFormat): + Container format of the video data. + """ + class ContainerFormat(proto.Enum): + r"""Container format of the video. + + Values: + CONTAINER_FORMAT_UNSPECIFIED (0): + The default type, not supposed to be used. + CONTAINER_FORMAT_MP4 (1): + Mp4 container format. + """ + CONTAINER_FORMAT_UNSPECIFIED = 0 + CONTAINER_FORMAT_MP4 = 1 + + container_format: 'IngestAssetRequest.Config.VideoType.ContainerFormat' = proto.Field( + proto.ENUM, + number=1, + enum='IngestAssetRequest.Config.VideoType.ContainerFormat', + ) + + video_type: 'IngestAssetRequest.Config.VideoType' = proto.Field( + proto.MESSAGE, + number=2, + oneof='data_type', + message='IngestAssetRequest.Config.VideoType', + ) + asset: str = proto.Field( + proto.STRING, + number=1, + ) + + class TimeIndexedData(proto.Message): + r"""Contains the data and the corresponding time range this data + is for. + + Attributes: + data (bytes): + Data to be ingested. + temporal_partition (google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition): + Time range of the data. + """ + + data: bytes = proto.Field( + proto.BYTES, + number=1, + ) + temporal_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + + config: Config = proto.Field( + proto.MESSAGE, + number=1, + oneof='streaming_request', + message=Config, + ) + time_indexed_data: TimeIndexedData = proto.Field( + proto.MESSAGE, + number=2, + oneof='streaming_request', + message=TimeIndexedData, + ) + + +class IngestAssetResponse(proto.Message): + r"""Response message for IngestAsset API. + + Attributes: + successfully_ingested_partition (google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition): + Time range of the data that has been + successfully ingested. + """ + + successfully_ingested_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=1, + message='Partition.TemporalPartition', + ) + + +class ClipAssetRequest(proto.Message): + r"""Request message for ClipAsset API. + + Attributes: + name (str): + Required. The resource name of the asset to request clips + for. Form: + 'projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}' + temporal_partition (google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition): + Required. The time range to request clips + for. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + temporal_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + + +class ClipAssetResponse(proto.Message): + r"""Response message for ClipAsset API. + + Attributes: + time_indexed_uris (MutableSequence[google.cloud.visionai_v1alpha1.types.ClipAssetResponse.TimeIndexedUri]): + A list of signed uris to download the video + clips that cover the requested time range + ordered by time. + """ + + class TimeIndexedUri(proto.Message): + r"""Signed uri with corresponding time range. + + Attributes: + temporal_partition (google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition): + Time range of the video that the uri is for. + uri (str): + Signed uri to download the video clip. + """ + + temporal_partition: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=1, + message='Partition.TemporalPartition', + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + time_indexed_uris: MutableSequence[TimeIndexedUri] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=TimeIndexedUri, + ) + + +class GenerateHlsUriRequest(proto.Message): + r"""Request message for GenerateHlsUri API. + + Attributes: + name (str): + Required. The resource name of the asset to request clips + for. Form: + 'projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}' + temporal_partitions (MutableSequence[google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition]): + Required. The time range to request clips + for. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + temporal_partitions: MutableSequence['Partition.TemporalPartition'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + + +class GenerateHlsUriResponse(proto.Message): + r"""Response message for GenerateHlsUri API. + + Attributes: + uri (str): + A signed uri to download the HLS manifest + corresponding to the requested times. + temporal_partitions (MutableSequence[google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition]): + A list of temporal partitions of the content + returned in the order they appear in the stream. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + temporal_partitions: MutableSequence['Partition.TemporalPartition'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + + +class SearchAssetsRequest(proto.Message): + r"""Request message for SearchAssets. + + Attributes: + corpus (str): + Required. The parent corpus to search. Form: + \`projects/{project_id}/locations/{location_id}/corpora/{corpus_id}' + page_size (int): + The number of results to be returned in this page. If it's + 0, the server will decide the appropriate page_size. + page_token (str): + The continuation token to fetch the next + page. If empty, it means it is fetching the + first page. + content_time_ranges (google.cloud.visionai_v1alpha1.types.DateTimeRangeArray): + Time ranges that matching video content must fall within. If + no ranges are provided, there will be no time restriction. + This field is treated just like the criteria below, but + defined separately for convenience as it is used frequently. + Note that if the end_time is in the future, it will be + clamped to the time the request was received. + criteria (MutableSequence[google.cloud.visionai_v1alpha1.types.Criteria]): + Criteria applied to search results. + facet_selections (MutableSequence[google.cloud.visionai_v1alpha1.types.FacetGroup]): + Stores most recent facet selection state. + Only facet groups with user's selection will be + presented here. Selection state is either + selected or unselected. Only selected facet + buckets will be used as search criteria. + result_annotation_keys (MutableSequence[str]): + A list of annotation keys to specify the annotations to be + retrieved and returned with each search result. Annotation + granularity must be GRANULARITY_ASSET_LEVEL and its search + strategy must not be NO_SEARCH. + """ + + corpus: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + content_time_ranges: 'DateTimeRangeArray' = proto.Field( + proto.MESSAGE, + number=5, + message='DateTimeRangeArray', + ) + criteria: MutableSequence['Criteria'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Criteria', + ) + facet_selections: MutableSequence['FacetGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='FacetGroup', + ) + result_annotation_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + + +class DeleteAssetMetadata(proto.Message): + r"""The metadata for DeleteAsset API that embeds in + [metadata][google.longrunning.Operation.metadata] field. + + """ + + +class AnnotationMatchingResult(proto.Message): + r"""Stores the criteria-annotation matching results for each + search result item. + + Attributes: + criteria (google.cloud.visionai_v1alpha1.types.Criteria): + The criteria used for matching. It can be an + input search criteria or a criteria converted + from a facet selection. + matched_annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.Annotation]): + Matched annotations for the criteria. + status (google.rpc.status_pb2.Status): + Status of the match result. Possible values: + FAILED_PRECONDITION - the criteria is not eligible for + match. OK - matching is performed. + """ + + criteria: 'Criteria' = proto.Field( + proto.MESSAGE, + number=1, + message='Criteria', + ) + matched_annotations: MutableSequence['Annotation'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Annotation', + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + + +class SearchResultItem(proto.Message): + r"""Search result contains asset name and corresponding time + ranges. + + Attributes: + asset (str): + The resource name of the asset. Form: + 'projects/{project_number}/locations/{location_id}/corpora/{corpus_id}/assets/{asset_id}' + segments (MutableSequence[google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition]): + The matched asset segments. Deprecated: please use singular + ``segment`` field. + segment (google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition): + The matched asset segment. + requested_annotations (MutableSequence[google.cloud.visionai_v1alpha1.types.Annotation]): + Search result annotations specified by + result_annotation_keys in search request. + annotation_matching_results (MutableSequence[google.cloud.visionai_v1alpha1.types.AnnotationMatchingResult]): + Criteria or facet-selection based annotation matching + results associated to this search result item. Only contains + results for criteria or facet_selections with + fetch_matched_annotations=true. + """ + + asset: str = proto.Field( + proto.STRING, + number=1, + ) + segments: MutableSequence['Partition.TemporalPartition'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Partition.TemporalPartition', + ) + segment: 'Partition.TemporalPartition' = proto.Field( + proto.MESSAGE, + number=5, + message='Partition.TemporalPartition', + ) + requested_annotations: MutableSequence['Annotation'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Annotation', + ) + annotation_matching_results: MutableSequence['AnnotationMatchingResult'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AnnotationMatchingResult', + ) + + +class SearchAssetsResponse(proto.Message): + r"""Response message for SearchAssets. + + Attributes: + search_result_items (MutableSequence[google.cloud.visionai_v1alpha1.types.SearchResultItem]): + Returned search results. + next_page_token (str): + The next-page continuation token. + facet_results (MutableSequence[google.cloud.visionai_v1alpha1.types.FacetGroup]): + Facet search results of a given query, which + contains user's already-selected facet values + and updated facet search results. + """ + + @property + def raw_page(self): + return self + + search_result_items: MutableSequence['SearchResultItem'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchResultItem', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + facet_results: MutableSequence['FacetGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='FacetGroup', + ) + + +class IntRange(proto.Message): + r"""Integer range type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start (int): + Start of the int range. + + This field is a member of `oneof`_ ``_start``. + end (int): + End of the int range. + + This field is a member of `oneof`_ ``_end``. + """ + + start: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + end: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + +class FloatRange(proto.Message): + r"""Float range type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start (float): + Start of the float range. + + This field is a member of `oneof`_ ``_start``. + end (float): + End of the float range. + + This field is a member of `oneof`_ ``_end``. + """ + + start: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + end: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + +class StringArray(proto.Message): + r"""A list of string-type values. + + Attributes: + txt_values (MutableSequence[str]): + String type values. + """ + + txt_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class IntRangeArray(proto.Message): + r"""A list of integer range values. + + Attributes: + int_ranges (MutableSequence[google.cloud.visionai_v1alpha1.types.IntRange]): + Int range values. + """ + + int_ranges: MutableSequence['IntRange'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IntRange', + ) + + +class FloatRangeArray(proto.Message): + r"""A list of float range values. + + Attributes: + float_ranges (MutableSequence[google.cloud.visionai_v1alpha1.types.FloatRange]): + Float range values. + """ + + float_ranges: MutableSequence['FloatRange'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FloatRange', + ) + + +class DateTimeRange(proto.Message): + r"""Datetime range type. + + Attributes: + start (google.type.datetime_pb2.DateTime): + Start date time. + end (google.type.datetime_pb2.DateTime): + End data time. + """ + + start: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=1, + message=datetime_pb2.DateTime, + ) + end: datetime_pb2.DateTime = proto.Field( + proto.MESSAGE, + number=2, + message=datetime_pb2.DateTime, + ) + + +class DateTimeRangeArray(proto.Message): + r"""A list of datetime range values. + + Attributes: + date_time_ranges (MutableSequence[google.cloud.visionai_v1alpha1.types.DateTimeRange]): + Date time ranges. + """ + + date_time_ranges: MutableSequence['DateTimeRange'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DateTimeRange', + ) + + +class CircleArea(proto.Message): + r"""Representation of a circle area. + + Attributes: + latitude (float): + Latitude of circle area's center. Degrees [-90 .. 90] + longitude (float): + Longitude of circle area's center. Degrees [-180 .. 180] + radius_meter (float): + Radius of the circle area in meters. + """ + + latitude: float = proto.Field( + proto.DOUBLE, + number=1, + ) + longitude: float = proto.Field( + proto.DOUBLE, + number=2, + ) + radius_meter: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + +class GeoLocationArray(proto.Message): + r"""A list of locations. + + Attributes: + circle_areas (MutableSequence[google.cloud.visionai_v1alpha1.types.CircleArea]): + A list of circle areas. + """ + + circle_areas: MutableSequence['CircleArea'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CircleArea', + ) + + +class BoolValue(proto.Message): + r""" + + Attributes: + value (bool): + + """ + + value: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class Criteria(proto.Message): + r"""Filter criteria applied to current search results. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text_array (google.cloud.visionai_v1alpha1.types.StringArray): + The text values associated with the field. + + This field is a member of `oneof`_ ``value``. + int_range_array (google.cloud.visionai_v1alpha1.types.IntRangeArray): + The integer ranges associated with the field. + + This field is a member of `oneof`_ ``value``. + float_range_array (google.cloud.visionai_v1alpha1.types.FloatRangeArray): + The float ranges associated with the field. + + This field is a member of `oneof`_ ``value``. + date_time_range_array (google.cloud.visionai_v1alpha1.types.DateTimeRangeArray): + The datetime ranges associated with the + field. + + This field is a member of `oneof`_ ``value``. + geo_location_array (google.cloud.visionai_v1alpha1.types.GeoLocationArray): + Geo Location array. + + This field is a member of `oneof`_ ``value``. + bool_value (google.cloud.visionai_v1alpha1.types.BoolValue): + A Boolean value. + + This field is a member of `oneof`_ ``value``. + field (str): + The UGA field or ML field to apply filtering + criteria. + fetch_matched_annotations (bool): + If true, return query matched annotations for this criteria. + This option is only applicable for partition level + annotations and supports the following data types: + + - INTEGER + - FLOAT + - STRING (DataSchema.SearchStrategy.EXACT_SEARCH only) + - BOOLEAN + """ + + text_array: 'StringArray' = proto.Field( + proto.MESSAGE, + number=2, + oneof='value', + message='StringArray', + ) + int_range_array: 'IntRangeArray' = proto.Field( + proto.MESSAGE, + number=3, + oneof='value', + message='IntRangeArray', + ) + float_range_array: 'FloatRangeArray' = proto.Field( + proto.MESSAGE, + number=4, + oneof='value', + message='FloatRangeArray', + ) + date_time_range_array: 'DateTimeRangeArray' = proto.Field( + proto.MESSAGE, + number=5, + oneof='value', + message='DateTimeRangeArray', + ) + geo_location_array: 'GeoLocationArray' = proto.Field( + proto.MESSAGE, + number=6, + oneof='value', + message='GeoLocationArray', + ) + bool_value: 'BoolValue' = proto.Field( + proto.MESSAGE, + number=7, + oneof='value', + message='BoolValue', + ) + field: str = proto.Field( + proto.STRING, + number=1, + ) + fetch_matched_annotations: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class Partition(proto.Message): + r"""Partition to specify the partition in time and space for + sub-asset level annotation. + + Attributes: + temporal_partition (google.cloud.visionai_v1alpha1.types.Partition.TemporalPartition): + Partition of asset in time. + spatial_partition (google.cloud.visionai_v1alpha1.types.Partition.SpatialPartition): + Partition of asset in space. + """ + + class TemporalPartition(proto.Message): + r"""Partition of asset in UTC Epoch time. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of the partition. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the partition. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class SpatialPartition(proto.Message): + r"""Partition of asset in space. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + x_min (int): + The minimum x coordinate value. + + This field is a member of `oneof`_ ``_x_min``. + y_min (int): + The minimum y coordinate value. + + This field is a member of `oneof`_ ``_y_min``. + x_max (int): + The maximum x coordinate value. + + This field is a member of `oneof`_ ``_x_max``. + y_max (int): + The maximum y coordinate value. + + This field is a member of `oneof`_ ``_y_max``. + """ + + x_min: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + y_min: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + x_max: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + y_max: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + + temporal_partition: TemporalPartition = proto.Field( + proto.MESSAGE, + number=1, + message=TemporalPartition, + ) + spatial_partition: SpatialPartition = proto.Field( + proto.MESSAGE, + number=2, + message=SpatialPartition, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/mypy.ini b/owl-bot-staging/google-cloud-visionai/v1alpha1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/noxfile.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/noxfile.py new file mode 100644 index 000000000000..6af33505cf72 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/noxfile.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-visionai' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/visionai_v1alpha1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + +@nox.session(python=ALL_PYTHON[-1]) +def prerelease_deps(session): + """Run the unit test suite against pre-release versions of dependencies.""" + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/visionai_v1alpha1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.visionai.v1alpha1.json b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.visionai.v1alpha1.json new file mode 100644 index 000000000000..f7d1e3f46ede --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.visionai.v1alpha1.json @@ -0,0 +1,14391 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.visionai.v1alpha1", + "version": "v1alpha1" + } + ], + "language": "PYTHON", + "name": "google-cloud-visionai", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.add_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.AddApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "AddApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.AddApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "add_application_stream_input" + }, + "description": "Sample for AddApplicationStreamInput", + "file": "visionai_v1alpha1_generated_app_platform_add_application_stream_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_AddApplicationStreamInput_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_add_application_stream_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.add_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.AddApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "AddApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.AddApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "add_application_stream_input" + }, + "description": "Sample for AddApplicationStreamInput", + "file": "visionai_v1alpha1_generated_app_platform_add_application_stream_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_AddApplicationStreamInput_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_add_application_stream_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.create_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_application_instances" + }, + "description": "Sample for CreateApplicationInstances", + "file": "visionai_v1alpha1_generated_app_platform_create_application_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateApplicationInstances_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_application_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.create_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_application_instances" + }, + "description": "Sample for CreateApplicationInstances", + "file": "visionai_v1alpha1_generated_app_platform_create_application_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateApplicationInstances_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_application_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.create_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateApplicationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1alpha1.types.Application" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_application" + }, + "description": "Sample for CreateApplication", + "file": "visionai_v1alpha1_generated_app_platform_create_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateApplication_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.create_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateApplicationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1alpha1.types.Application" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_application" + }, + "description": "Sample for CreateApplication", + "file": "visionai_v1alpha1_generated_app_platform_create_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateApplication_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.create_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateDraftRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1alpha1.types.Draft" + }, + { + "name": "draft_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_draft" + }, + "description": "Sample for CreateDraft", + "file": "visionai_v1alpha1_generated_app_platform_create_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateDraft_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.create_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateDraftRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1alpha1.types.Draft" + }, + { + "name": "draft_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_draft" + }, + "description": "Sample for CreateDraft", + "file": "visionai_v1alpha1_generated_app_platform_create_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateDraft_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.create_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1alpha1.types.Processor" + }, + { + "name": "processor_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "visionai_v1alpha1_generated_app_platform_create_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateProcessor_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.create_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.CreateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "CreateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateProcessorRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1alpha1.types.Processor" + }, + { + "name": "processor_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_processor" + }, + "description": "Sample for CreateProcessor", + "file": "visionai_v1alpha1_generated_app_platform_create_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_CreateProcessor_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_create_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.delete_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_application_instances" + }, + "description": "Sample for DeleteApplicationInstances", + "file": "visionai_v1alpha1_generated_app_platform_delete_application_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteApplicationInstances_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_application_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.delete_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_application_instances" + }, + "description": "Sample for DeleteApplicationInstances", + "file": "visionai_v1alpha1_generated_app_platform_delete_application_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteApplicationInstances_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_application_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.delete_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_application" + }, + "description": "Sample for DeleteApplication", + "file": "visionai_v1alpha1_generated_app_platform_delete_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteApplication_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.delete_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_application" + }, + "description": "Sample for DeleteApplication", + "file": "visionai_v1alpha1_generated_app_platform_delete_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteApplication_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.delete_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_draft" + }, + "description": "Sample for DeleteDraft", + "file": "visionai_v1alpha1_generated_app_platform_delete_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteDraft_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.delete_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_draft" + }, + "description": "Sample for DeleteDraft", + "file": "visionai_v1alpha1_generated_app_platform_delete_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteDraft_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.delete_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "visionai_v1alpha1_generated_app_platform_delete_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteProcessor_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.delete_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeleteProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeleteProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_processor" + }, + "description": "Sample for DeleteProcessor", + "file": "visionai_v1alpha1_generated_app_platform_delete_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeleteProcessor_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_delete_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.deploy_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "deploy_application" + }, + "description": "Sample for DeployApplication", + "file": "visionai_v1alpha1_generated_app_platform_deploy_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeployApplication_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_deploy_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.deploy_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.DeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "DeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "deploy_application" + }, + "description": "Sample for DeployApplication", + "file": "visionai_v1alpha1_generated_app_platform_deploy_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_DeployApplication_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_deploy_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.get_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Application", + "shortName": "get_application" + }, + "description": "Sample for GetApplication", + "file": "visionai_v1alpha1_generated_app_platform_get_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetApplication_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.get_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Application", + "shortName": "get_application" + }, + "description": "Sample for GetApplication", + "file": "visionai_v1alpha1_generated_app_platform_get_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetApplication_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.get_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Draft", + "shortName": "get_draft" + }, + "description": "Sample for GetDraft", + "file": "visionai_v1alpha1_generated_app_platform_get_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetDraft_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.get_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetDraftRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Draft", + "shortName": "get_draft" + }, + "description": "Sample for GetDraft", + "file": "visionai_v1alpha1_generated_app_platform_get_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetDraft_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetInstance", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "visionai_v1alpha1_generated_app_platform_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetInstance_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.get_instance", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetInstance", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "visionai_v1alpha1_generated_app_platform_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetInstance_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.get_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Processor", + "shortName": "get_processor" + }, + "description": "Sample for GetProcessor", + "file": "visionai_v1alpha1_generated_app_platform_get_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetProcessor_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.get_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.GetProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "GetProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetProcessorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Processor", + "shortName": "get_processor" + }, + "description": "Sample for GetProcessor", + "file": "visionai_v1alpha1_generated_app_platform_get_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_GetProcessor_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_get_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.list_applications", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListApplications", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListApplications" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListApplicationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListApplicationsAsyncPager", + "shortName": "list_applications" + }, + "description": "Sample for ListApplications", + "file": "visionai_v1alpha1_generated_app_platform_list_applications_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListApplications_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_applications_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.list_applications", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListApplications", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListApplications" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListApplicationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListApplicationsPager", + "shortName": "list_applications" + }, + "description": "Sample for ListApplications", + "file": "visionai_v1alpha1_generated_app_platform_list_applications_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListApplications_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_applications_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.list_drafts", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListDrafts", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListDrafts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListDraftsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListDraftsAsyncPager", + "shortName": "list_drafts" + }, + "description": "Sample for ListDrafts", + "file": "visionai_v1alpha1_generated_app_platform_list_drafts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListDrafts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_drafts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.list_drafts", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListDrafts", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListDrafts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListDraftsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListDraftsPager", + "shortName": "list_drafts" + }, + "description": "Sample for ListDrafts", + "file": "visionai_v1alpha1_generated_app_platform_list_drafts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListDrafts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_drafts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "visionai_v1alpha1_generated_app_platform_list_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListInstances_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.list_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "visionai_v1alpha1_generated_app_platform_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListInstances_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.list_prebuilt_processors", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListPrebuiltProcessors", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListPrebuiltProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsResponse", + "shortName": "list_prebuilt_processors" + }, + "description": "Sample for ListPrebuiltProcessors", + "file": "visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListPrebuiltProcessors_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.list_prebuilt_processors", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListPrebuiltProcessors", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListPrebuiltProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.ListPrebuiltProcessorsResponse", + "shortName": "list_prebuilt_processors" + }, + "description": "Sample for ListPrebuiltProcessors", + "file": "visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListPrebuiltProcessors_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.list_processors", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListProcessors", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListProcessorsAsyncPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "visionai_v1alpha1_generated_app_platform_list_processors_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListProcessors_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_processors_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.list_processors", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.ListProcessors", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "ListProcessors" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListProcessorsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.app_platform.pagers.ListProcessorsPager", + "shortName": "list_processors" + }, + "description": "Sample for ListProcessors", + "file": "visionai_v1alpha1_generated_app_platform_list_processors_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_ListProcessors_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_list_processors_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.remove_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.RemoveApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "RemoveApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.RemoveApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "remove_application_stream_input" + }, + "description": "Sample for RemoveApplicationStreamInput", + "file": "visionai_v1alpha1_generated_app_platform_remove_application_stream_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_RemoveApplicationStreamInput_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_remove_application_stream_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.remove_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.RemoveApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "RemoveApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.RemoveApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "remove_application_stream_input" + }, + "description": "Sample for RemoveApplicationStreamInput", + "file": "visionai_v1alpha1_generated_app_platform_remove_application_stream_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_RemoveApplicationStreamInput_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_remove_application_stream_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.undeploy_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UndeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UndeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UndeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "undeploy_application" + }, + "description": "Sample for UndeployApplication", + "file": "visionai_v1alpha1_generated_app_platform_undeploy_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UndeployApplication_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_undeploy_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.undeploy_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UndeployApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UndeployApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UndeployApplicationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "undeploy_application" + }, + "description": "Sample for UndeployApplication", + "file": "visionai_v1alpha1_generated_app_platform_undeploy_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UndeployApplication_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_undeploy_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.update_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "application_instances", + "type": "MutableSequence[google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_application_instances" + }, + "description": "Sample for UpdateApplicationInstances", + "file": "visionai_v1alpha1_generated_app_platform_update_application_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateApplicationInstances_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_application_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.update_application_instances", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateApplicationInstances", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "application_instances", + "type": "MutableSequence[google.cloud.visionai_v1alpha1.types.UpdateApplicationInstancesRequest.UpdateApplicationInstance]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_application_instances" + }, + "description": "Sample for UpdateApplicationInstances", + "file": "visionai_v1alpha1_generated_app_platform_update_application_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateApplicationInstances_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_application_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.update_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_application_stream_input" + }, + "description": "Sample for UpdateApplicationStreamInput", + "file": "visionai_v1alpha1_generated_app_platform_update_application_stream_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateApplicationStreamInput_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_application_stream_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.update_application_stream_input", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateApplicationStreamInput", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplicationStreamInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateApplicationStreamInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_application_stream_input" + }, + "description": "Sample for UpdateApplicationStreamInput", + "file": "visionai_v1alpha1_generated_app_platform_update_application_stream_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateApplicationStreamInput_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_application_stream_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.update_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateApplicationRequest" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1alpha1.types.Application" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_application" + }, + "description": "Sample for UpdateApplication", + "file": "visionai_v1alpha1_generated_app_platform_update_application_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateApplication_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_application_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.update_application", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateApplication", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateApplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateApplicationRequest" + }, + { + "name": "application", + "type": "google.cloud.visionai_v1alpha1.types.Application" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_application" + }, + "description": "Sample for UpdateApplication", + "file": "visionai_v1alpha1_generated_app_platform_update_application_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateApplication_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_application_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.update_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateDraftRequest" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1alpha1.types.Draft" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_draft" + }, + "description": "Sample for UpdateDraft", + "file": "visionai_v1alpha1_generated_app_platform_update_draft_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateDraft_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_draft_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.update_draft", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateDraft", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateDraft" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateDraftRequest" + }, + { + "name": "draft", + "type": "google.cloud.visionai_v1alpha1.types.Draft" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_draft" + }, + "description": "Sample for UpdateDraft", + "file": "visionai_v1alpha1_generated_app_platform_update_draft_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateDraft_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_draft_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient", + "shortName": "AppPlatformAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformAsyncClient.update_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateProcessorRequest" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1alpha1.types.Processor" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_processor" + }, + "description": "Sample for UpdateProcessor", + "file": "visionai_v1alpha1_generated_app_platform_update_processor_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateProcessor_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_processor_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient", + "shortName": "AppPlatformClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.AppPlatformClient.update_processor", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform.UpdateProcessor", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.AppPlatform", + "shortName": "AppPlatform" + }, + "shortName": "UpdateProcessor" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateProcessorRequest" + }, + { + "name": "processor", + "type": "google.cloud.visionai_v1alpha1.types.Processor" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_processor" + }, + "description": "Sample for UpdateProcessor", + "file": "visionai_v1alpha1_generated_app_platform_update_processor_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_AppPlatform_UpdateProcessor_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_app_platform_update_processor_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient.create_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.CreateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateAnalysisRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1alpha1.types.Analysis" + }, + { + "name": "analysis_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_analysis" + }, + "description": "Sample for CreateAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_create_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_CreateAnalysis_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_create_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient.create_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.CreateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "CreateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateAnalysisRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1alpha1.types.Analysis" + }, + { + "name": "analysis_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_analysis" + }, + "description": "Sample for CreateAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_create_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_CreateAnalysis_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_create_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient.delete_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.DeleteAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_analysis" + }, + "description": "Sample for DeleteAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_delete_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_DeleteAnalysis_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_delete_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient.delete_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.DeleteAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "DeleteAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_analysis" + }, + "description": "Sample for DeleteAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_delete_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_DeleteAnalysis_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_delete_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient.get_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.GetAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Analysis", + "shortName": "get_analysis" + }, + "description": "Sample for GetAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_get_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_GetAnalysis_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_get_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient.get_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.GetAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "GetAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetAnalysisRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Analysis", + "shortName": "get_analysis" + }, + "description": "Sample for GetAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_get_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_GetAnalysis_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_get_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient.list_analyses", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.ListAnalyses", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListAnalyses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListAnalysesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.live_video_analytics.pagers.ListAnalysesAsyncPager", + "shortName": "list_analyses" + }, + "description": "Sample for ListAnalyses", + "file": "visionai_v1alpha1_generated_live_video_analytics_list_analyses_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_ListAnalyses_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_list_analyses_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient.list_analyses", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.ListAnalyses", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "ListAnalyses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListAnalysesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.live_video_analytics.pagers.ListAnalysesPager", + "shortName": "list_analyses" + }, + "description": "Sample for ListAnalyses", + "file": "visionai_v1alpha1_generated_live_video_analytics_list_analyses_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_ListAnalyses_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_list_analyses_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient", + "shortName": "LiveVideoAnalyticsAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsAsyncClient.update_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.UpdateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateAnalysisRequest" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1alpha1.types.Analysis" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_analysis" + }, + "description": "Sample for UpdateAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_update_analysis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_UpdateAnalysis_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_update_analysis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient", + "shortName": "LiveVideoAnalyticsClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.LiveVideoAnalyticsClient.update_analysis", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics.UpdateAnalysis", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.LiveVideoAnalytics", + "shortName": "LiveVideoAnalytics" + }, + "shortName": "UpdateAnalysis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateAnalysisRequest" + }, + { + "name": "analysis", + "type": "google.cloud.visionai_v1alpha1.types.Analysis" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_analysis" + }, + "description": "Sample for UpdateAnalysis", + "file": "visionai_v1alpha1_generated_live_video_analytics_update_analysis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_LiveVideoAnalytics_UpdateAnalysis_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_live_video_analytics_update_analysis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient.acquire_lease", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.AcquireLease", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "AcquireLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.AcquireLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Lease", + "shortName": "acquire_lease" + }, + "description": "Sample for AcquireLease", + "file": "visionai_v1alpha1_generated_streaming_service_acquire_lease_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_AcquireLease_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_acquire_lease_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient.acquire_lease", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.AcquireLease", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "AcquireLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.AcquireLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Lease", + "shortName": "acquire_lease" + }, + "description": "Sample for AcquireLease", + "file": "visionai_v1alpha1_generated_streaming_service_acquire_lease_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_AcquireLease_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_acquire_lease_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient.receive_events", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.ReceiveEvents", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceiveEvents" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.ReceiveEventsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.ReceiveEventsResponse]", + "shortName": "receive_events" + }, + "description": "Sample for ReceiveEvents", + "file": "visionai_v1alpha1_generated_streaming_service_receive_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_ReceiveEvents_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_receive_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient.receive_events", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.ReceiveEvents", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceiveEvents" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.ReceiveEventsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.ReceiveEventsResponse]", + "shortName": "receive_events" + }, + "description": "Sample for ReceiveEvents", + "file": "visionai_v1alpha1_generated_streaming_service_receive_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_ReceiveEvents_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_receive_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient.receive_packets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.ReceivePackets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceivePackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.ReceivePacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.ReceivePacketsResponse]", + "shortName": "receive_packets" + }, + "description": "Sample for ReceivePackets", + "file": "visionai_v1alpha1_generated_streaming_service_receive_packets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_ReceivePackets_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_receive_packets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient.receive_packets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.ReceivePackets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReceivePackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.ReceivePacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.ReceivePacketsResponse]", + "shortName": "receive_packets" + }, + "description": "Sample for ReceivePackets", + "file": "visionai_v1alpha1_generated_streaming_service_receive_packets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_ReceivePackets_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_receive_packets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient.release_lease", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.ReleaseLease", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReleaseLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ReleaseLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.ReleaseLeaseResponse", + "shortName": "release_lease" + }, + "description": "Sample for ReleaseLease", + "file": "visionai_v1alpha1_generated_streaming_service_release_lease_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_ReleaseLease_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_release_lease_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient.release_lease", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.ReleaseLease", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "ReleaseLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ReleaseLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.ReleaseLeaseResponse", + "shortName": "release_lease" + }, + "description": "Sample for ReleaseLease", + "file": "visionai_v1alpha1_generated_streaming_service_release_lease_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_ReleaseLease_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_release_lease_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient.renew_lease", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.RenewLease", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "RenewLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.RenewLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Lease", + "shortName": "renew_lease" + }, + "description": "Sample for RenewLease", + "file": "visionai_v1alpha1_generated_streaming_service_renew_lease_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_RenewLease_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_renew_lease_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient.renew_lease", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.RenewLease", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "RenewLease" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.RenewLeaseRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Lease", + "shortName": "renew_lease" + }, + "description": "Sample for RenewLease", + "file": "visionai_v1alpha1_generated_streaming_service_renew_lease_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_RenewLease_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_renew_lease_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient", + "shortName": "StreamingServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceAsyncClient.send_packets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.SendPackets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "SendPackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.SendPacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.SendPacketsResponse]", + "shortName": "send_packets" + }, + "description": "Sample for SendPackets", + "file": "visionai_v1alpha1_generated_streaming_service_send_packets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_SendPackets_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_send_packets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient", + "shortName": "StreamingServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamingServiceClient.send_packets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService.SendPackets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamingService", + "shortName": "StreamingService" + }, + "shortName": "SendPackets" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.SendPacketsRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.SendPacketsResponse]", + "shortName": "send_packets" + }, + "description": "Sample for SendPackets", + "file": "visionai_v1alpha1_generated_streaming_service_send_packets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamingService_SendPackets_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streaming_service_send_packets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.create_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1alpha1.types.Cluster" + }, + { + "name": "cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_cluster" + }, + "description": "Sample for CreateCluster", + "file": "visionai_v1alpha1_generated_streams_service_create_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateCluster_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.create_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1alpha1.types.Cluster" + }, + { + "name": "cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_cluster" + }, + "description": "Sample for CreateCluster", + "file": "visionai_v1alpha1_generated_streams_service_create_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateCluster_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.create_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1alpha1.types.Event" + }, + { + "name": "event_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_event" + }, + "description": "Sample for CreateEvent", + "file": "visionai_v1alpha1_generated_streams_service_create_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateEvent_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.create_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1alpha1.types.Event" + }, + { + "name": "event_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_event" + }, + "description": "Sample for CreateEvent", + "file": "visionai_v1alpha1_generated_streams_service_create_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateEvent_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.create_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1alpha1.types.Series" + }, + { + "name": "series_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_series" + }, + "description": "Sample for CreateSeries", + "file": "visionai_v1alpha1_generated_streams_service_create_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateSeries_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.create_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1alpha1.types.Series" + }, + { + "name": "series_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_series" + }, + "description": "Sample for CreateSeries", + "file": "visionai_v1alpha1_generated_streams_service_create_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateSeries_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.create_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateStreamRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1alpha1.types.Stream" + }, + { + "name": "stream_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_stream" + }, + "description": "Sample for CreateStream", + "file": "visionai_v1alpha1_generated_streams_service_create_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateStream_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.create_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.CreateStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "CreateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateStreamRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1alpha1.types.Stream" + }, + { + "name": "stream_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_stream" + }, + "description": "Sample for CreateStream", + "file": "visionai_v1alpha1_generated_streams_service_create_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_CreateStream_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_create_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.delete_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "visionai_v1alpha1_generated_streams_service_delete_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteCluster_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.delete_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "visionai_v1alpha1_generated_streams_service_delete_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteCluster_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.delete_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_event" + }, + "description": "Sample for DeleteEvent", + "file": "visionai_v1alpha1_generated_streams_service_delete_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteEvent_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.delete_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_event" + }, + "description": "Sample for DeleteEvent", + "file": "visionai_v1alpha1_generated_streams_service_delete_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteEvent_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.delete_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_series" + }, + "description": "Sample for DeleteSeries", + "file": "visionai_v1alpha1_generated_streams_service_delete_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteSeries_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.delete_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_series" + }, + "description": "Sample for DeleteSeries", + "file": "visionai_v1alpha1_generated_streams_service_delete_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteSeries_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.delete_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_stream" + }, + "description": "Sample for DeleteStream", + "file": "visionai_v1alpha1_generated_streams_service_delete_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteStream_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.delete_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.DeleteStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "DeleteStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_stream" + }, + "description": "Sample for DeleteStream", + "file": "visionai_v1alpha1_generated_streams_service_delete_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_DeleteStream_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_delete_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.generate_stream_hls_token", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GenerateStreamHlsToken", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GenerateStreamHlsToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenRequest" + }, + { + "name": "stream", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenResponse", + "shortName": "generate_stream_hls_token" + }, + "description": "Sample for GenerateStreamHlsToken", + "file": "visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GenerateStreamHlsToken_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.generate_stream_hls_token", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GenerateStreamHlsToken", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GenerateStreamHlsToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenRequest" + }, + { + "name": "stream", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.GenerateStreamHlsTokenResponse", + "shortName": "generate_stream_hls_token" + }, + "description": "Sample for GenerateStreamHlsToken", + "file": "visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GenerateStreamHlsToken_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.get_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "visionai_v1alpha1_generated_streams_service_get_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetCluster_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.get_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "visionai_v1alpha1_generated_streams_service_get_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetCluster_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.get_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Event", + "shortName": "get_event" + }, + "description": "Sample for GetEvent", + "file": "visionai_v1alpha1_generated_streams_service_get_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetEvent_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.get_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetEventRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Event", + "shortName": "get_event" + }, + "description": "Sample for GetEvent", + "file": "visionai_v1alpha1_generated_streams_service_get_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetEvent_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.get_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Series", + "shortName": "get_series" + }, + "description": "Sample for GetSeries", + "file": "visionai_v1alpha1_generated_streams_service_get_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetSeries_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.get_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetSeriesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Series", + "shortName": "get_series" + }, + "description": "Sample for GetSeries", + "file": "visionai_v1alpha1_generated_streams_service_get_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetSeries_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.get_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Stream", + "shortName": "get_stream" + }, + "description": "Sample for GetStream", + "file": "visionai_v1alpha1_generated_streams_service_get_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetStream_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.get_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.GetStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "GetStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Stream", + "shortName": "get_stream" + }, + "description": "Sample for GetStream", + "file": "visionai_v1alpha1_generated_streams_service_get_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_GetStream_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_get_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.list_clusters", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListClusters", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListClustersAsyncPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "visionai_v1alpha1_generated_streams_service_list_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListClusters_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.list_clusters", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListClusters", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListClustersPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "visionai_v1alpha1_generated_streams_service_list_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListClusters_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.list_events", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListEvents", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListEventsAsyncPager", + "shortName": "list_events" + }, + "description": "Sample for ListEvents", + "file": "visionai_v1alpha1_generated_streams_service_list_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListEvents_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.list_events", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListEvents", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListEventsPager", + "shortName": "list_events" + }, + "description": "Sample for ListEvents", + "file": "visionai_v1alpha1_generated_streams_service_list_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListEvents_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.list_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListSeriesAsyncPager", + "shortName": "list_series" + }, + "description": "Sample for ListSeries", + "file": "visionai_v1alpha1_generated_streams_service_list_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListSeries_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.list_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListSeriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListSeriesPager", + "shortName": "list_series" + }, + "description": "Sample for ListSeries", + "file": "visionai_v1alpha1_generated_streams_service_list_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListSeries_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.list_streams", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListStreams", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListStreams" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListStreamsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListStreamsAsyncPager", + "shortName": "list_streams" + }, + "description": "Sample for ListStreams", + "file": "visionai_v1alpha1_generated_streams_service_list_streams_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListStreams_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_streams_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.list_streams", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.ListStreams", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "ListStreams" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListStreamsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.streams_service.pagers.ListStreamsPager", + "shortName": "list_streams" + }, + "description": "Sample for ListStreams", + "file": "visionai_v1alpha1_generated_streams_service_list_streams_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_ListStreams_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_list_streams_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.materialize_channel", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.MaterializeChannel", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "MaterializeChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.MaterializeChannelRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel", + "type": "google.cloud.visionai_v1alpha1.types.Channel" + }, + { + "name": "channel_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "materialize_channel" + }, + "description": "Sample for MaterializeChannel", + "file": "visionai_v1alpha1_generated_streams_service_materialize_channel_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_MaterializeChannel_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_materialize_channel_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.materialize_channel", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.MaterializeChannel", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "MaterializeChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.MaterializeChannelRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel", + "type": "google.cloud.visionai_v1alpha1.types.Channel" + }, + { + "name": "channel_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "materialize_channel" + }, + "description": "Sample for MaterializeChannel", + "file": "visionai_v1alpha1_generated_streams_service_materialize_channel_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_MaterializeChannel_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_materialize_channel_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.update_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1alpha1.types.Cluster" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "visionai_v1alpha1_generated_streams_service_update_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateCluster_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.update_cluster", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateCluster", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.visionai_v1alpha1.types.Cluster" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "visionai_v1alpha1_generated_streams_service_update_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateCluster_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.update_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateEventRequest" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1alpha1.types.Event" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_event" + }, + "description": "Sample for UpdateEvent", + "file": "visionai_v1alpha1_generated_streams_service_update_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateEvent_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.update_event", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateEvent", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateEventRequest" + }, + { + "name": "event", + "type": "google.cloud.visionai_v1alpha1.types.Event" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_event" + }, + "description": "Sample for UpdateEvent", + "file": "visionai_v1alpha1_generated_streams_service_update_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateEvent_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.update_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateSeriesRequest" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1alpha1.types.Series" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_series" + }, + "description": "Sample for UpdateSeries", + "file": "visionai_v1alpha1_generated_streams_service_update_series_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateSeries_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_series_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.update_series", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateSeries", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateSeries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateSeriesRequest" + }, + { + "name": "series", + "type": "google.cloud.visionai_v1alpha1.types.Series" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_series" + }, + "description": "Sample for UpdateSeries", + "file": "visionai_v1alpha1_generated_streams_service_update_series_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateSeries_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_series_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient", + "shortName": "StreamsServiceAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceAsyncClient.update_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateStreamRequest" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1alpha1.types.Stream" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_stream" + }, + "description": "Sample for UpdateStream", + "file": "visionai_v1alpha1_generated_streams_service_update_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateStream_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient", + "shortName": "StreamsServiceClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.StreamsServiceClient.update_stream", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService.UpdateStream", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.StreamsService", + "shortName": "StreamsService" + }, + "shortName": "UpdateStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateStreamRequest" + }, + { + "name": "stream", + "type": "google.cloud.visionai_v1alpha1.types.Stream" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_stream" + }, + "description": "Sample for UpdateStream", + "file": "visionai_v1alpha1_generated_streams_service_update_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_StreamsService_UpdateStream_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_streams_service_update_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.clip_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ClipAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ClipAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ClipAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.ClipAssetResponse", + "shortName": "clip_asset" + }, + "description": "Sample for ClipAsset", + "file": "visionai_v1alpha1_generated_warehouse_clip_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ClipAsset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_clip_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.clip_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ClipAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ClipAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ClipAssetRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.ClipAssetResponse", + "shortName": "clip_asset" + }, + "description": "Sample for ClipAsset", + "file": "visionai_v1alpha1_generated_warehouse_clip_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ClipAsset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_clip_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.create_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateAnnotationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1alpha1.types.Annotation" + }, + { + "name": "annotation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Annotation", + "shortName": "create_annotation" + }, + "description": "Sample for CreateAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_create_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateAnnotation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.create_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateAnnotationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1alpha1.types.Annotation" + }, + { + "name": "annotation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Annotation", + "shortName": "create_annotation" + }, + "description": "Sample for CreateAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_create_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateAnnotation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.create_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateAssetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1alpha1.types.Asset" + }, + { + "name": "asset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Asset", + "shortName": "create_asset" + }, + "description": "Sample for CreateAsset", + "file": "visionai_v1alpha1_generated_warehouse_create_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateAsset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.create_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateAssetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1alpha1.types.Asset" + }, + { + "name": "asset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Asset", + "shortName": "create_asset" + }, + "description": "Sample for CreateAsset", + "file": "visionai_v1alpha1_generated_warehouse_create_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateAsset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.create_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateCorpusRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1alpha1.types.Corpus" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_corpus" + }, + "description": "Sample for CreateCorpus", + "file": "visionai_v1alpha1_generated_warehouse_create_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateCorpus_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.create_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateCorpusRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1alpha1.types.Corpus" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_corpus" + }, + "description": "Sample for CreateCorpus", + "file": "visionai_v1alpha1_generated_warehouse_create_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateCorpus_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.create_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateDataSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1alpha1.types.DataSchema" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.DataSchema", + "shortName": "create_data_schema" + }, + "description": "Sample for CreateDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_create_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateDataSchema_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.create_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateDataSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1alpha1.types.DataSchema" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.DataSchema", + "shortName": "create_data_schema" + }, + "description": "Sample for CreateDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_create_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateDataSchema_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.create_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateSearchConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1alpha1.types.SearchConfig" + }, + { + "name": "search_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.SearchConfig", + "shortName": "create_search_config" + }, + "description": "Sample for CreateSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_create_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateSearchConfig_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.create_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.CreateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "CreateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.CreateSearchConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1alpha1.types.SearchConfig" + }, + { + "name": "search_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.SearchConfig", + "shortName": "create_search_config" + }, + "description": "Sample for CreateSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_create_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_CreateSearchConfig_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_create_search_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.delete_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_annotation" + }, + "description": "Sample for DeleteAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_delete_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteAnnotation_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.delete_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_annotation" + }, + "description": "Sample for DeleteAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_delete_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteAnnotation_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.delete_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_asset" + }, + "description": "Sample for DeleteAsset", + "file": "visionai_v1alpha1_generated_warehouse_delete_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteAsset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.delete_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_asset" + }, + "description": "Sample for DeleteAsset", + "file": "visionai_v1alpha1_generated_warehouse_delete_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteAsset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.delete_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_corpus" + }, + "description": "Sample for DeleteCorpus", + "file": "visionai_v1alpha1_generated_warehouse_delete_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteCorpus_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.delete_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_corpus" + }, + "description": "Sample for DeleteCorpus", + "file": "visionai_v1alpha1_generated_warehouse_delete_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteCorpus_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.delete_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_data_schema" + }, + "description": "Sample for DeleteDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_delete_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteDataSchema_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.delete_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_data_schema" + }, + "description": "Sample for DeleteDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_delete_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteDataSchema_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.delete_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_search_config" + }, + "description": "Sample for DeleteSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_delete_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteSearchConfig_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.delete_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.DeleteSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "DeleteSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.DeleteSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_search_config" + }, + "description": "Sample for DeleteSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_delete_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_DeleteSearchConfig_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_delete_search_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.generate_hls_uri", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GenerateHlsUri", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GenerateHlsUri" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GenerateHlsUriRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.GenerateHlsUriResponse", + "shortName": "generate_hls_uri" + }, + "description": "Sample for GenerateHlsUri", + "file": "visionai_v1alpha1_generated_warehouse_generate_hls_uri_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GenerateHlsUri_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_generate_hls_uri_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.generate_hls_uri", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GenerateHlsUri", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GenerateHlsUri" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GenerateHlsUriRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.GenerateHlsUriResponse", + "shortName": "generate_hls_uri" + }, + "description": "Sample for GenerateHlsUri", + "file": "visionai_v1alpha1_generated_warehouse_generate_hls_uri_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GenerateHlsUri_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_generate_hls_uri_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.get_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Annotation", + "shortName": "get_annotation" + }, + "description": "Sample for GetAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_get_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetAnnotation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.get_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetAnnotationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Annotation", + "shortName": "get_annotation" + }, + "description": "Sample for GetAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_get_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetAnnotation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.get_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Asset", + "shortName": "get_asset" + }, + "description": "Sample for GetAsset", + "file": "visionai_v1alpha1_generated_warehouse_get_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetAsset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.get_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Asset", + "shortName": "get_asset" + }, + "description": "Sample for GetAsset", + "file": "visionai_v1alpha1_generated_warehouse_get_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetAsset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.get_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Corpus", + "shortName": "get_corpus" + }, + "description": "Sample for GetCorpus", + "file": "visionai_v1alpha1_generated_warehouse_get_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetCorpus_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.get_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetCorpusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Corpus", + "shortName": "get_corpus" + }, + "description": "Sample for GetCorpus", + "file": "visionai_v1alpha1_generated_warehouse_get_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetCorpus_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.get_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.DataSchema", + "shortName": "get_data_schema" + }, + "description": "Sample for GetDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_get_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetDataSchema_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.get_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetDataSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.DataSchema", + "shortName": "get_data_schema" + }, + "description": "Sample for GetDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_get_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetDataSchema_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.get_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.SearchConfig", + "shortName": "get_search_config" + }, + "description": "Sample for GetSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_get_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetSearchConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.get_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.GetSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "GetSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.GetSearchConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.SearchConfig", + "shortName": "get_search_config" + }, + "description": "Sample for GetSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_get_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_GetSearchConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_get_search_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.ingest_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.IngestAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "IngestAsset" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.IngestAssetRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.IngestAssetResponse]", + "shortName": "ingest_asset" + }, + "description": "Sample for IngestAsset", + "file": "visionai_v1alpha1_generated_warehouse_ingest_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_IngestAsset_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_ingest_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.ingest_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.IngestAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "IngestAsset" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.visionai_v1alpha1.types.IngestAssetRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.cloud.visionai_v1alpha1.types.IngestAssetResponse]", + "shortName": "ingest_asset" + }, + "description": "Sample for IngestAsset", + "file": "visionai_v1alpha1_generated_warehouse_ingest_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_IngestAsset_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_ingest_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.list_annotations", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListAnnotations", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAnnotations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListAnnotationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAnnotationsAsyncPager", + "shortName": "list_annotations" + }, + "description": "Sample for ListAnnotations", + "file": "visionai_v1alpha1_generated_warehouse_list_annotations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListAnnotations_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_annotations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.list_annotations", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListAnnotations", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAnnotations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListAnnotationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAnnotationsPager", + "shortName": "list_annotations" + }, + "description": "Sample for ListAnnotations", + "file": "visionai_v1alpha1_generated_warehouse_list_annotations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListAnnotations_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_annotations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListAssets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListAssetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "visionai_v1alpha1_generated_warehouse_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListAssets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.list_assets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListAssets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListAssetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "visionai_v1alpha1_generated_warehouse_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListAssets_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.list_corpora", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListCorpora", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListCorpora" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListCorporaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListCorporaAsyncPager", + "shortName": "list_corpora" + }, + "description": "Sample for ListCorpora", + "file": "visionai_v1alpha1_generated_warehouse_list_corpora_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListCorpora_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_corpora_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.list_corpora", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListCorpora", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListCorpora" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListCorporaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListCorporaPager", + "shortName": "list_corpora" + }, + "description": "Sample for ListCorpora", + "file": "visionai_v1alpha1_generated_warehouse_list_corpora_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListCorpora_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_corpora_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.list_data_schemas", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListDataSchemas", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListDataSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListDataSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListDataSchemasAsyncPager", + "shortName": "list_data_schemas" + }, + "description": "Sample for ListDataSchemas", + "file": "visionai_v1alpha1_generated_warehouse_list_data_schemas_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListDataSchemas_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_data_schemas_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.list_data_schemas", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListDataSchemas", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListDataSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListDataSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListDataSchemasPager", + "shortName": "list_data_schemas" + }, + "description": "Sample for ListDataSchemas", + "file": "visionai_v1alpha1_generated_warehouse_list_data_schemas_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListDataSchemas_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_data_schemas_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.list_search_configs", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListSearchConfigs", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListSearchConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListSearchConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListSearchConfigsAsyncPager", + "shortName": "list_search_configs" + }, + "description": "Sample for ListSearchConfigs", + "file": "visionai_v1alpha1_generated_warehouse_list_search_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListSearchConfigs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_search_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.list_search_configs", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.ListSearchConfigs", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "ListSearchConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.ListSearchConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.ListSearchConfigsPager", + "shortName": "list_search_configs" + }, + "description": "Sample for ListSearchConfigs", + "file": "visionai_v1alpha1_generated_warehouse_list_search_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_ListSearchConfigs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_list_search_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.search_assets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.SearchAssets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "SearchAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.SearchAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.SearchAssetsAsyncPager", + "shortName": "search_assets" + }, + "description": "Sample for SearchAssets", + "file": "visionai_v1alpha1_generated_warehouse_search_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_SearchAssets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_search_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.search_assets", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.SearchAssets", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "SearchAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.SearchAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.services.warehouse.pagers.SearchAssetsPager", + "shortName": "search_assets" + }, + "description": "Sample for SearchAssets", + "file": "visionai_v1alpha1_generated_warehouse_search_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_SearchAssets_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_search_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.update_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateAnnotationRequest" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1alpha1.types.Annotation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Annotation", + "shortName": "update_annotation" + }, + "description": "Sample for UpdateAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_update_annotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateAnnotation_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_annotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.update_annotation", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateAnnotation", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAnnotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateAnnotationRequest" + }, + { + "name": "annotation", + "type": "google.cloud.visionai_v1alpha1.types.Annotation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Annotation", + "shortName": "update_annotation" + }, + "description": "Sample for UpdateAnnotation", + "file": "visionai_v1alpha1_generated_warehouse_update_annotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateAnnotation_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_annotation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.update_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateAssetRequest" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1alpha1.types.Asset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Asset", + "shortName": "update_asset" + }, + "description": "Sample for UpdateAsset", + "file": "visionai_v1alpha1_generated_warehouse_update_asset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateAsset_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_asset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.update_asset", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateAsset", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateAssetRequest" + }, + { + "name": "asset", + "type": "google.cloud.visionai_v1alpha1.types.Asset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Asset", + "shortName": "update_asset" + }, + "description": "Sample for UpdateAsset", + "file": "visionai_v1alpha1_generated_warehouse_update_asset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateAsset_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_asset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.update_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateCorpusRequest" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1alpha1.types.Corpus" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Corpus", + "shortName": "update_corpus" + }, + "description": "Sample for UpdateCorpus", + "file": "visionai_v1alpha1_generated_warehouse_update_corpus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateCorpus_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_corpus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.update_corpus", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateCorpus", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateCorpus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateCorpusRequest" + }, + { + "name": "corpus", + "type": "google.cloud.visionai_v1alpha1.types.Corpus" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.Corpus", + "shortName": "update_corpus" + }, + "description": "Sample for UpdateCorpus", + "file": "visionai_v1alpha1_generated_warehouse_update_corpus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateCorpus_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_corpus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.update_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateDataSchemaRequest" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1alpha1.types.DataSchema" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.DataSchema", + "shortName": "update_data_schema" + }, + "description": "Sample for UpdateDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_update_data_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateDataSchema_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_data_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.update_data_schema", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateDataSchema", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateDataSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateDataSchemaRequest" + }, + { + "name": "data_schema", + "type": "google.cloud.visionai_v1alpha1.types.DataSchema" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.DataSchema", + "shortName": "update_data_schema" + }, + "description": "Sample for UpdateDataSchema", + "file": "visionai_v1alpha1_generated_warehouse_update_data_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateDataSchema_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_data_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient", + "shortName": "WarehouseAsyncClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseAsyncClient.update_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateSearchConfigRequest" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1alpha1.types.SearchConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.SearchConfig", + "shortName": "update_search_config" + }, + "description": "Sample for UpdateSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_update_search_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateSearchConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_search_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient", + "shortName": "WarehouseClient" + }, + "fullName": "google.cloud.visionai_v1alpha1.WarehouseClient.update_search_config", + "method": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse.UpdateSearchConfig", + "service": { + "fullName": "google.cloud.visionai.v1alpha1.Warehouse", + "shortName": "Warehouse" + }, + "shortName": "UpdateSearchConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.visionai_v1alpha1.types.UpdateSearchConfigRequest" + }, + { + "name": "search_config", + "type": "google.cloud.visionai_v1alpha1.types.SearchConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.visionai_v1alpha1.types.SearchConfig", + "shortName": "update_search_config" + }, + "description": "Sample for UpdateSearchConfig", + "file": "visionai_v1alpha1_generated_warehouse_update_search_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "visionai_v1alpha1_generated_Warehouse_UpdateSearchConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "visionai_v1alpha1_generated_warehouse_update_search_config_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_add_application_stream_input_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_add_application_stream_input_async.py new file mode 100644 index 000000000000..badb94104acf --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_add_application_stream_input_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_AddApplicationStreamInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_add_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_AddApplicationStreamInput_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_add_application_stream_input_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_add_application_stream_input_sync.py new file mode 100644 index 000000000000..660977fabb99 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_add_application_stream_input_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_AddApplicationStreamInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_add_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AddApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.add_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_AddApplicationStreamInput_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_async.py new file mode 100644 index 000000000000..eb3b439fb762 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_instances_async.py new file mode 100644 index 000000000000..3d9a67867f1b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_instances_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateApplicationInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application_instances = visionai_v1alpha1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateApplicationInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_instances_sync.py new file mode 100644 index 000000000000..ffc4e9b61328 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_instances_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateApplicationInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + application_instances = visionai_v1alpha1.ApplicationInstance() + application_instances.instance_id = "instance_id_value" + application_instances.instance.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationInstancesRequest( + name="name_value", + application_instances=application_instances, + ) + + # Make the request + operation = client.create_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateApplicationInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_sync.py new file mode 100644 index 000000000000..86d600fda535 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_application_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateApplicationRequest( + parent="parent_value", + application_id="application_id_value", + application=application, + ) + + # Make the request + operation = client.create_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_draft_async.py new file mode 100644 index 000000000000..7f8deba66b80 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_draft_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_draft_sync.py new file mode 100644 index 000000000000..3f4306a2b6f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_draft_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateDraftRequest( + parent="parent_value", + draft_id="draft_id_value", + draft=draft, + ) + + # Make the request + operation = client.create_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_processor_async.py new file mode 100644 index 000000000000..1c273c9ceb2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_processor_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_processor_sync.py new file mode 100644 index 000000000000..16d953d706b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_create_processor_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_CreateProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateProcessorRequest( + parent="parent_value", + processor_id="processor_id_value", + processor=processor, + ) + + # Make the request + operation = client.create_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_CreateProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_async.py new file mode 100644 index 000000000000..af2d1b78c6e8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_instances_async.py new file mode 100644 index 000000000000..a05bf7210fbb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_instances_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteApplicationInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteApplicationInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_instances_sync.py new file mode 100644 index 000000000000..6c8f2f03316e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_instances_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteApplicationInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationInstancesRequest( + name="name_value", + instance_ids=['instance_ids_value1', 'instance_ids_value2'], + ) + + # Make the request + operation = client.delete_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteApplicationInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_sync.py new file mode 100644 index 000000000000..4e9f9d5a8217 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_application_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_draft_async.py new file mode 100644 index 000000000000..4e1aecb8e1ee --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_draft_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_draft_sync.py new file mode 100644 index 000000000000..7f4fa98f5644 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_draft_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDraftRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_processor_async.py new file mode 100644 index 000000000000..fa2862b6814a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_processor_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_processor_sync.py new file mode 100644 index 000000000000..e51eb7bb6830 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_delete_processor_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeleteProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteProcessorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeleteProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_deploy_application_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_deploy_application_async.py new file mode 100644 index 000000000000..51b75e185b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_deploy_application_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeployApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_deploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeployApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_deploy_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_deploy_application_sync.py new file mode 100644 index 000000000000..bcc312066838 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_deploy_application_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_DeployApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_deploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.deploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_DeployApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_application_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_application_async.py new file mode 100644 index 000000000000..c1701dc70ff8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_application_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_application(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_application_sync.py new file mode 100644 index 000000000000..616fa6587905 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_application_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetApplicationRequest( + name="name_value", + ) + + # Make the request + response = client.get_application(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_draft_async.py new file mode 100644 index 000000000000..9c7c88979c4d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_draft_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = await client.get_draft(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_draft_sync.py new file mode 100644 index 000000000000..5f1963f6ee3c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_draft_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDraftRequest( + name="name_value", + ) + + # Make the request + response = client.get_draft(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_instance_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_instance_async.py new file mode 100644 index 000000000000..c76851514542 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_instance_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_instance(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetInstance_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_instance_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_instance_sync.py new file mode 100644 index 000000000000..bd23d48ad674 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_instance_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_instance(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetInstance_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_processor_async.py new file mode 100644 index 000000000000..f8974c34c111 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_processor_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_processor(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_processor_sync.py new file mode 100644 index 000000000000..f28dc053d46a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_get_processor_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_GetProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetProcessorRequest( + name="name_value", + ) + + # Make the request + response = client.get_processor(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_GetProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_applications_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_applications_async.py new file mode 100644 index 000000000000..a6a247fe305c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_applications_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListApplications +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListApplications_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_applications(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListApplications_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_applications_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_applications_sync.py new file mode 100644 index 000000000000..638a4cbb15ce --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_applications_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListApplications +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListApplications_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_applications(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListApplicationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applications(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListApplications_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_drafts_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_drafts_async.py new file mode 100644 index 000000000000..9c30a34201e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_drafts_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDrafts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListDrafts_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_drafts(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListDrafts_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_drafts_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_drafts_sync.py new file mode 100644 index 000000000000..0e1d3817a85a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_drafts_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDrafts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListDrafts_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_drafts(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDraftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_drafts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListDrafts_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_instances_async.py new file mode 100644 index 000000000000..1dd7f49dd4e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_instances_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_instances_sync.py new file mode 100644 index 000000000000..7916a1ce9063 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_instances_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_async.py new file mode 100644 index 000000000000..b84ef71c4c30 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPrebuiltProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListPrebuiltProcessors_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListPrebuiltProcessors_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_sync.py new file mode 100644 index 000000000000..96679714b7c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_prebuilt_processors_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPrebuiltProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListPrebuiltProcessors_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_prebuilt_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListPrebuiltProcessorsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_prebuilt_processors(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListPrebuiltProcessors_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_processors_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_processors_async.py new file mode 100644 index 000000000000..d233b1419266 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_processors_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListProcessors_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListProcessors_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_processors_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_processors_sync.py new file mode 100644 index 000000000000..778d0859dfc4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_list_processors_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProcessors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_ListProcessors_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_processors(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListProcessorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_processors(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_ListProcessors_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_remove_application_stream_input_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_remove_application_stream_input_async.py new file mode 100644 index 000000000000..cd720658110a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_remove_application_stream_input_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_RemoveApplicationStreamInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_RemoveApplicationStreamInput_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_remove_application_stream_input_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_remove_application_stream_input_sync.py new file mode 100644 index 000000000000..17f6fbcf1ab0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_remove_application_stream_input_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_RemoveApplicationStreamInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_remove_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RemoveApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.remove_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_RemoveApplicationStreamInput_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_undeploy_application_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_undeploy_application_async.py new file mode 100644 index 000000000000..3662b91ecbe0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_undeploy_application_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UndeployApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_undeploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UndeployApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_undeploy_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_undeploy_application_sync.py new file mode 100644 index 000000000000..d44add56b4a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_undeploy_application_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeployApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UndeployApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_undeploy_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UndeployApplicationRequest( + name="name_value", + ) + + # Make the request + operation = client.undeploy_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UndeployApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_async.py new file mode 100644 index 000000000000..aa86c147a69b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateApplication_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateApplication_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_instances_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_instances_async.py new file mode 100644 index 000000000000..10b06fc8023a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_instances_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateApplicationInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateApplicationInstances_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_instances_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_instances_sync.py new file mode 100644 index 000000000000..e7c830e7c221 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_instances_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateApplicationInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_application_instances(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationInstancesRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateApplicationInstances_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_stream_input_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_stream_input_async.py new file mode 100644 index 000000000000..dbdf3ef2d868 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_stream_input_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateApplicationStreamInput_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateApplicationStreamInput_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_stream_input_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_stream_input_sync.py new file mode 100644 index 000000000000..5455f49f993d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_stream_input_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplicationStreamInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateApplicationStreamInput_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_application_stream_input(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateApplicationStreamInputRequest( + name="name_value", + ) + + # Make the request + operation = client.update_application_stream_input(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateApplicationStreamInput_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_sync.py new file mode 100644 index 000000000000..214b5ee44c99 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_application_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApplication +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateApplication_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_application(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + application = visionai_v1alpha1.Application() + application.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateApplicationRequest( + application=application, + ) + + # Make the request + operation = client.update_application(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateApplication_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_draft_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_draft_async.py new file mode 100644 index 000000000000..d46e41dade3f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_draft_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateDraft_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateDraft_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_draft_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_draft_sync.py new file mode 100644 index 000000000000..106c1a89c430 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_draft_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDraft +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateDraft_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_draft(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + draft = visionai_v1alpha1.Draft() + draft.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateDraftRequest( + draft=draft, + ) + + # Make the request + operation = client.update_draft(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateDraft_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_processor_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_processor_async.py new file mode 100644 index 000000000000..99698f5e2a05 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_processor_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateProcessor_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformAsyncClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateProcessor_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_processor_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_processor_sync.py new file mode 100644 index 000000000000..2cd80e7a2e54 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_app_platform_update_processor_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProcessor +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_AppPlatform_UpdateProcessor_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_processor(): + # Create a client + client = visionai_v1alpha1.AppPlatformClient() + + # Initialize request argument(s) + processor = visionai_v1alpha1.Processor() + processor.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateProcessorRequest( + processor=processor, + ) + + # Make the request + operation = client.update_processor(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_AppPlatform_UpdateProcessor_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_create_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_create_analysis_async.py new file mode 100644 index 000000000000..c9616e06d255 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_create_analysis_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_CreateAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_CreateAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_create_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_create_analysis_sync.py new file mode 100644 index 000000000000..d8a770b52115 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_create_analysis_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_CreateAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnalysisRequest( + parent="parent_value", + analysis_id="analysis_id_value", + ) + + # Make the request + operation = client.create_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_CreateAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_delete_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_delete_analysis_async.py new file mode 100644 index 000000000000..5caa4c00d3a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_delete_analysis_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_DeleteAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_DeleteAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_delete_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_delete_analysis_sync.py new file mode 100644 index 000000000000..c739db952997 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_delete_analysis_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_DeleteAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnalysisRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_DeleteAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_get_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_get_analysis_async.py new file mode 100644 index 000000000000..bf51364a3b46 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_get_analysis_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_GetAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = await client.get_analysis(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_GetAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_get_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_get_analysis_sync.py new file mode 100644 index 000000000000..04ed2c5f1ded --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_get_analysis_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_GetAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnalysisRequest( + name="name_value", + ) + + # Make the request + response = client.get_analysis(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_GetAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_list_analyses_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_list_analyses_async.py new file mode 100644 index 000000000000..a2dd4339108e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_list_analyses_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnalyses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_ListAnalyses_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_analyses(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_ListAnalyses_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_list_analyses_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_list_analyses_sync.py new file mode 100644 index 000000000000..0c66c36b969e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_list_analyses_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnalyses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_ListAnalyses_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_analyses(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnalysesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_analyses(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_ListAnalyses_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_update_analysis_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_update_analysis_async.py new file mode 100644 index 000000000000..20608e6cd7aa --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_update_analysis_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_UpdateAnalysis_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_UpdateAnalysis_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_update_analysis_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_update_analysis_sync.py new file mode 100644 index 000000000000..d837ab4a7e80 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_live_video_analytics_update_analysis_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnalysis +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_LiveVideoAnalytics_UpdateAnalysis_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_analysis(): + # Create a client + client = visionai_v1alpha1.LiveVideoAnalyticsClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnalysisRequest( + ) + + # Make the request + operation = client.update_analysis(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_LiveVideoAnalytics_UpdateAnalysis_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_acquire_lease_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_acquire_lease_async.py new file mode 100644 index 000000000000..d3e2ffc1fe52 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_acquire_lease_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcquireLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_AcquireLease_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_acquire_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AcquireLeaseRequest( + ) + + # Make the request + response = await client.acquire_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_AcquireLease_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_acquire_lease_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_acquire_lease_sync.py new file mode 100644 index 000000000000..d5d5f4e54b15 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_acquire_lease_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcquireLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_AcquireLease_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_acquire_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.AcquireLeaseRequest( + ) + + # Make the request + response = client.acquire_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_AcquireLease_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_events_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_events_async.py new file mode 100644 index 000000000000..5909040ca38e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_events_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceiveEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_ReceiveEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_receive_events(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_events(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_ReceiveEvents_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_events_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_events_sync.py new file mode 100644 index 000000000000..52e4b73449b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_events_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceiveEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_ReceiveEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_receive_events(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceiveEventsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceiveEventsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_events(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_ReceiveEvents_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_packets_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_packets_async.py new file mode 100644 index 000000000000..172152bedc77 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_packets_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceivePackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_ReceivePackets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_receive_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.receive_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_ReceivePackets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_packets_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_packets_sync.py new file mode 100644 index 000000000000..0d17d7eed3b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_receive_packets_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReceivePackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_ReceivePackets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_receive_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReceivePacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.ReceivePacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.receive_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_ReceivePackets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_release_lease_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_release_lease_async.py new file mode 100644 index 000000000000..65865ea227ea --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_release_lease_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReleaseLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_ReleaseLease_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_release_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReleaseLeaseRequest( + ) + + # Make the request + response = await client.release_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_ReleaseLease_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_release_lease_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_release_lease_sync.py new file mode 100644 index 000000000000..a4fd7b658ab7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_release_lease_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReleaseLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_ReleaseLease_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_release_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ReleaseLeaseRequest( + ) + + # Make the request + response = client.release_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_ReleaseLease_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_renew_lease_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_renew_lease_async.py new file mode 100644 index 000000000000..bbda5104353b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_renew_lease_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RenewLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_RenewLease_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_renew_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RenewLeaseRequest( + ) + + # Make the request + response = await client.renew_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_RenewLease_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_renew_lease_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_renew_lease_sync.py new file mode 100644 index 000000000000..6df1b63f8db8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_renew_lease_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RenewLease +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_RenewLease_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_renew_lease(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.RenewLeaseRequest( + ) + + # Make the request + response = client.renew_lease(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_RenewLease_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_send_packets_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_send_packets_async.py new file mode 100644 index 000000000000..582601a606ab --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_send_packets_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendPackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_SendPackets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_send_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.send_packets(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_SendPackets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_send_packets_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_send_packets_sync.py new file mode 100644 index 000000000000..461cd498f155 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streaming_service_send_packets_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendPackets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamingService_SendPackets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_send_packets(): + # Create a client + client = visionai_v1alpha1.StreamingServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SendPacketsRequest( + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.SendPacketsRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.send_packets(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_StreamingService_SendPackets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_cluster_async.py new file mode 100644 index 000000000000..b0fc94109524 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_cluster_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_cluster_sync.py new file mode 100644 index 000000000000..2a98dad67445 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_cluster_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_event_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_event_async.py new file mode 100644 index 000000000000..f455434b3604 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_event_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_event_sync.py new file mode 100644 index 000000000000..fa215eef4b29 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_event_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", + ) + + # Make the request + operation = client.create_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_series_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_series_async.py new file mode 100644 index 000000000000..19b800b08582 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_series_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_series_sync.py new file mode 100644 index 000000000000..686d8acc3bb7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_series_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.CreateSeriesRequest( + parent="parent_value", + series_id="series_id_value", + series=series, + ) + + # Make the request + operation = client.create_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_stream_async.py new file mode 100644 index 000000000000..0825724e2e33 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_stream_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_stream_sync.py new file mode 100644 index 000000000000..bd13a8d2d954 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_create_stream_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_CreateStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateStreamRequest( + parent="parent_value", + stream_id="stream_id_value", + ) + + # Make the request + operation = client.create_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_CreateStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_cluster_async.py new file mode 100644 index 000000000000..208f65fd22a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_cluster_sync.py new file mode 100644 index 000000000000..e6d95bf13d77 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_event_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_event_async.py new file mode 100644 index 000000000000..93943aebbb8e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_event_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_event_sync.py new file mode 100644 index 000000000000..711ef80260bc --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_event_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteEventRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_series_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_series_async.py new file mode 100644 index 000000000000..f2eb8fa5f90d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_series_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_series_sync.py new file mode 100644 index 000000000000..4567514e0b5f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_series_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSeriesRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_stream_async.py new file mode 100644 index 000000000000..d441e4ed65ec --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_stream_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_stream_sync.py new file mode 100644 index 000000000000..0181de30b6f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_delete_stream_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_DeleteStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteStreamRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_DeleteStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_async.py new file mode 100644 index 000000000000..db78909f9991 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateStreamHlsToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GenerateStreamHlsToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = await client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GenerateStreamHlsToken_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_sync.py new file mode 100644 index 000000000000..0a1951f69167 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_generate_stream_hls_token_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateStreamHlsToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GenerateStreamHlsToken_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_generate_stream_hls_token(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateStreamHlsTokenRequest( + stream="stream_value", + ) + + # Make the request + response = client.generate_stream_hls_token(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GenerateStreamHlsToken_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_cluster_async.py new file mode 100644 index 000000000000..5c9746775cf6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_cluster_sync.py new file mode 100644 index 000000000000..37838fcecb81 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_event_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_event_async.py new file mode 100644 index 000000000000..16ec2180bdc6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_event_sync.py new file mode 100644 index 000000000000..59207a9bbb72 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_event(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_series_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_series_async.py new file mode 100644 index 000000000000..99917731fa77 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_series_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_series(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_series_sync.py new file mode 100644 index 000000000000..c5f98b7d389e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_series_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSeriesRequest( + name="name_value", + ) + + # Make the request + response = client.get_series(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_stream_async.py new file mode 100644 index 000000000000..fefba1bd5b6e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_stream_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = await client.get_stream(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_stream_sync.py new file mode 100644 index 000000000000..61bc66244ef9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_get_stream_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_GetStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetStreamRequest( + name="name_value", + ) + + # Make the request + response = client.get_stream(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_GetStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_clusters_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_clusters_async.py new file mode 100644 index 000000000000..28147231038c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListClusters_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_clusters(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListClusters_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_clusters_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_clusters_sync.py new file mode 100644 index 000000000000..95ca5386ad7a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListClusters_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_clusters(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListClusters_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_events_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_events_async.py new file mode 100644 index 000000000000..f13754e08a4d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_events_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_events(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListEvents_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_events_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_events_sync.py new file mode 100644 index 000000000000..670b50ba9d14 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_events_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_events(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_events(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListEvents_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_series_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_series_async.py new file mode 100644 index 000000000000..680f6ab1ae69 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_series_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_series_sync.py new file mode 100644 index 000000000000..98af60796716 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_series_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSeriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_series(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_streams_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_streams_async.py new file mode 100644 index 000000000000..ebfd64a1ea5c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_streams_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListStreams +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListStreams_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_streams(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListStreams_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_streams_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_streams_sync.py new file mode 100644 index 000000000000..9e88214f7928 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_list_streams_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListStreams +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_ListStreams_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_streams(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_ListStreams_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_materialize_channel_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_materialize_channel_async.py new file mode 100644 index 000000000000..975159355339 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_materialize_channel_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MaterializeChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_MaterializeChannel_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_materialize_channel(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + channel = visionai_v1alpha1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1alpha1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_MaterializeChannel_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_materialize_channel_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_materialize_channel_sync.py new file mode 100644 index 000000000000..d7f1b6e9fc3d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_materialize_channel_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MaterializeChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_MaterializeChannel_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_materialize_channel(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + channel = visionai_v1alpha1.Channel() + channel.stream = "stream_value" + channel.event = "event_value" + + request = visionai_v1alpha1.MaterializeChannelRequest( + parent="parent_value", + channel_id="channel_id_value", + channel=channel, + ) + + # Make the request + operation = client.materialize_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_MaterializeChannel_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_cluster_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_cluster_async.py new file mode 100644 index 000000000000..11dd0d1494ae --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_cluster_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateCluster_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_cluster_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_cluster_sync.py new file mode 100644 index 000000000000..530af2bb77dc --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_cluster_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_cluster(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateClusterRequest( + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateCluster_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_event_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_event_async.py new file mode 100644 index 000000000000..aa5e4c8058dc --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_event_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateEvent_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_event_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_event_sync.py new file mode 100644 index 000000000000..aa9d5df49942 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_event_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_event(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateEventRequest( + ) + + # Make the request + operation = client.update_event(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateEvent_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_series_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_series_async.py new file mode 100644 index 000000000000..3d2b7455e675 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_series_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateSeries_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateSeries_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_series_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_series_sync.py new file mode 100644 index 000000000000..8491dea4f868 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_series_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSeries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateSeries_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_series(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + series = visionai_v1alpha1.Series() + series.stream = "stream_value" + series.event = "event_value" + + request = visionai_v1alpha1.UpdateSeriesRequest( + series=series, + ) + + # Make the request + operation = client.update_series(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateSeries_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_stream_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_stream_async.py new file mode 100644 index 000000000000..0fef149f26a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_stream_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateStream_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateStream_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_stream_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_stream_sync.py new file mode 100644 index 000000000000..f9becb3bda5e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_streams_service_update_stream_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_StreamsService_UpdateStream_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_stream(): + # Create a client + client = visionai_v1alpha1.StreamsServiceClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateStreamRequest( + ) + + # Make the request + operation = client.update_stream(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_StreamsService_UpdateStream_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_clip_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_clip_asset_async.py new file mode 100644 index 000000000000..0daf09cf89ed --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_clip_asset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClipAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ClipAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_clip_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.clip_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ClipAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_clip_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_clip_asset_sync.py new file mode 100644 index 000000000000..fc498982262d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_clip_asset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClipAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ClipAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_clip_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ClipAssetRequest( + name="name_value", + ) + + # Make the request + response = client.clip_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ClipAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_annotation_async.py new file mode 100644 index 000000000000..227a8d7da3b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_annotation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_annotation_sync.py new file mode 100644 index 000000000000..3b65e6cdd6b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_annotation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAnnotationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_asset_async.py new file mode 100644 index 000000000000..cacf8912bcaa --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_asset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_asset_sync.py new file mode 100644 index 000000000000..13c39247e4f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_asset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateAssetRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_corpus_async.py new file mode 100644 index 000000000000..530bbece0981 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_corpus_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_corpus_sync.py new file mode 100644 index 000000000000..781f01baffb0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_corpus_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.CreateCorpusRequest( + parent="parent_value", + corpus=corpus, + ) + + # Make the request + operation = client.create_corpus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_data_schema_async.py new file mode 100644 index 000000000000..5909938b273b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_data_schema_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = await client.create_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_data_schema_sync.py new file mode 100644 index 000000000000..6cd6bd236737 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_data_schema_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.CreateDataSchemaRequest( + parent="parent_value", + data_schema=data_schema, + ) + + # Make the request + response = client.create_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_search_config_async.py new file mode 100644 index 000000000000..01bbab08dc8d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_search_config_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_create_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = await client.create_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_search_config_sync.py new file mode 100644 index 000000000000..b504a1410c1d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_create_search_config_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_CreateSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_create_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.CreateSearchConfigRequest( + parent="parent_value", + search_config_id="search_config_id_value", + ) + + # Make the request + response = client.create_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_CreateSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_annotation_async.py new file mode 100644 index 000000000000..b585eb83229b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_annotation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + await client.delete_annotation(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_annotation_sync.py new file mode 100644 index 000000000000..fcdf13a28ac0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_annotation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAnnotationRequest( + name="name_value", + ) + + # Make the request + client.delete_annotation(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_asset_async.py new file mode 100644 index 000000000000..0a5dbd3fb19e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_asset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_DeleteAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_asset_sync.py new file mode 100644 index 000000000000..598e876e2f20 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_asset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteAssetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_asset(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_DeleteAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_corpus_async.py new file mode 100644 index 000000000000..643e868fb96b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_corpus_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + await client.delete_corpus(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_corpus_sync.py new file mode 100644 index 000000000000..9f52bbdfc690 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_corpus_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + client.delete_corpus(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_data_schema_async.py new file mode 100644 index 000000000000..0f0cbd26f0ac --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_data_schema_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_schema(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_data_schema_sync.py new file mode 100644 index 000000000000..f361d4136e85 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_data_schema_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteDataSchemaRequest( + name="name_value", + ) + + # Make the request + client.delete_data_schema(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_search_config_async.py new file mode 100644 index 000000000000..f3ce2ee0c8b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_search_config_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_delete_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_search_config(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_search_config_sync.py new file mode 100644 index 000000000000..103d78cbc16b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_delete_search_config_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_DeleteSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_delete_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.DeleteSearchConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_search_config(request=request) + + +# [END visionai_v1alpha1_generated_Warehouse_DeleteSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_generate_hls_uri_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_generate_hls_uri_async.py new file mode 100644 index 000000000000..6a6cdcd4f89f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_generate_hls_uri_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateHlsUri +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GenerateHlsUri_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_generate_hls_uri(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_hls_uri(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GenerateHlsUri_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_generate_hls_uri_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_generate_hls_uri_sync.py new file mode 100644 index 000000000000..c1ca56a8e49b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_generate_hls_uri_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateHlsUri +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GenerateHlsUri_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_generate_hls_uri(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GenerateHlsUriRequest( + name="name_value", + ) + + # Make the request + response = client.generate_hls_uri(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GenerateHlsUri_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_annotation_async.py new file mode 100644 index 000000000000..52ae1e16c6c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_annotation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_annotation_sync.py new file mode 100644 index 000000000000..a2297e329f12 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_annotation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAnnotationRequest( + name="name_value", + ) + + # Make the request + response = client.get_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_asset_async.py new file mode 100644 index 000000000000..4509e47ac63f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_asset_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_asset_sync.py new file mode 100644 index 000000000000..0e3f395e3864 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_asset_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetAssetRequest( + name="name_value", + ) + + # Make the request + response = client.get_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_corpus_async.py new file mode 100644 index 000000000000..bb88148d708b --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_corpus_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_corpus_sync.py new file mode 100644 index 000000000000..893d13282bca --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_corpus_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = client.get_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_data_schema_async.py new file mode 100644 index 000000000000..58d390e785b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_data_schema_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_data_schema_sync.py new file mode 100644 index 000000000000..4bf3f7d51bf6 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_data_schema_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetDataSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_search_config_async.py new file mode 100644 index 000000000000..3a1c7cdeef95 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_search_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_get_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_search_config_sync.py new file mode 100644 index 000000000000..e50dc8ef5f50 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_get_search_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_GetSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_get_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.GetSearchConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_GetSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_ingest_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_ingest_asset_async.py new file mode 100644 index 000000000000..73110a985987 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_ingest_asset_async.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for IngestAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_IngestAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_ingest_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + config = visionai_v1alpha1.Config() + config.asset = "asset_value" + + request = visionai_v1alpha1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.ingest_asset(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_IngestAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_ingest_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_ingest_asset_sync.py new file mode 100644 index 000000000000..065532fd164c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_ingest_asset_sync.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for IngestAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_IngestAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_ingest_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + config = visionai_v1alpha1.Config() + config.asset = "asset_value" + + request = visionai_v1alpha1.IngestAssetRequest( + config=config, + ) + + # This method expects an iterator which contains + # 'visionai_v1alpha1.IngestAssetRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.ingest_asset(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_IngestAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_annotations_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_annotations_async.py new file mode 100644 index 000000000000..875fcf600447 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_annotations_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnnotations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListAnnotations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_annotations(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListAnnotations_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_annotations_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_annotations_sync.py new file mode 100644 index 000000000000..a964191c88df --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_annotations_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAnnotations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListAnnotations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_annotations(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAnnotationsRequest( + ) + + # Make the request + page_result = client.list_annotations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListAnnotations_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_assets_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_assets_async.py new file mode 100644 index 000000000000..71ebd019c657 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_assets_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_assets_sync.py new file mode 100644 index 000000000000..6f82a4ff7510 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_corpora_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_corpora_async.py new file mode 100644 index 000000000000..7bc8bed1ba46 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_corpora_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCorpora +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListCorpora_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_corpora(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListCorpora_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_corpora_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_corpora_sync.py new file mode 100644 index 000000000000..883c3066feb7 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_corpora_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCorpora +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListCorpora_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_corpora(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListCorporaRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListCorpora_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_data_schemas_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_data_schemas_async.py new file mode 100644 index 000000000000..54978da53328 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_data_schemas_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListDataSchemas_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_data_schemas(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListDataSchemas_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_data_schemas_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_data_schemas_sync.py new file mode 100644 index 000000000000..a95112c72b8a --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_data_schemas_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListDataSchemas_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_data_schemas(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListDataSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListDataSchemas_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_search_configs_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_search_configs_async.py new file mode 100644 index 000000000000..daae5826dbfe --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_search_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSearchConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListSearchConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_list_search_configs(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListSearchConfigs_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_search_configs_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_search_configs_sync.py new file mode 100644 index 000000000000..40896e7a6b39 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_list_search_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSearchConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_ListSearchConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_list_search_configs(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.ListSearchConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_search_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_ListSearchConfigs_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_search_assets_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_search_assets_async.py new file mode 100644 index 000000000000..adbcac434ceb --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_search_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_SearchAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_search_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_SearchAssets_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_search_assets_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_search_assets_sync.py new file mode 100644 index 000000000000..57369f7ba6e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_search_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_SearchAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_search_assets(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.SearchAssetsRequest( + corpus="corpus_value", + ) + + # Make the request + page_result = client.search_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_SearchAssets_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_annotation_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_annotation_async.py new file mode 100644 index 000000000000..734b67f8da5d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_annotation_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateAnnotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnnotationRequest( + ) + + # Make the request + response = await client.update_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateAnnotation_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_annotation_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_annotation_sync.py new file mode 100644 index 000000000000..0f73bb241cc0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_annotation_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAnnotation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateAnnotation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_annotation(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAnnotationRequest( + ) + + # Make the request + response = client.update_annotation(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateAnnotation_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_asset_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_asset_async.py new file mode 100644 index 000000000000..5c27893cbbba --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_asset_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateAsset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAssetRequest( + ) + + # Make the request + response = await client.update_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateAsset_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_asset_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_asset_sync.py new file mode 100644 index 000000000000..4777d2a52094 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_asset_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAsset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateAsset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_asset(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateAssetRequest( + ) + + # Make the request + response = client.update_asset(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateAsset_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_corpus_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_corpus_async.py new file mode 100644 index 000000000000..482a93363c84 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_corpus_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateCorpus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = await client.update_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateCorpus_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_corpus_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_corpus_sync.py new file mode 100644 index 000000000000..a7a5aed6e40f --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_corpus_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCorpus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateCorpus_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_corpus(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + corpus = visionai_v1alpha1.Corpus() + corpus.display_name = "display_name_value" + + request = visionai_v1alpha1.UpdateCorpusRequest( + corpus=corpus, + ) + + # Make the request + response = client.update_corpus(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateCorpus_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_data_schema_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_data_schema_async.py new file mode 100644 index 000000000000..92c1aff80693 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_data_schema_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateDataSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = await client.update_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateDataSchema_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_data_schema_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_data_schema_sync.py new file mode 100644 index 000000000000..9bcfa70437ec --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_data_schema_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateDataSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_data_schema(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + data_schema = visionai_v1alpha1.DataSchema() + data_schema.key = "key_value" + + request = visionai_v1alpha1.UpdateDataSchemaRequest( + data_schema=data_schema, + ) + + # Make the request + response = client.update_data_schema(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateDataSchema_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_search_config_async.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_search_config_async.py new file mode 100644 index 000000000000..7831ee76a46c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_search_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateSearchConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +async def sample_update_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseAsyncClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateSearchConfigRequest( + ) + + # Make the request + response = await client.update_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateSearchConfig_async] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_search_config_sync.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_search_config_sync.py new file mode 100644 index 000000000000..0e0447c6aa0c --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/samples/generated_samples/visionai_v1alpha1_generated_warehouse_update_search_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSearchConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-visionai + + +# [START visionai_v1alpha1_generated_Warehouse_UpdateSearchConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import visionai_v1alpha1 + + +def sample_update_search_config(): + # Create a client + client = visionai_v1alpha1.WarehouseClient() + + # Initialize request argument(s) + request = visionai_v1alpha1.UpdateSearchConfigRequest( + ) + + # Make the request + response = client.update_search_config(request=request) + + # Handle the response + print(response) + +# [END visionai_v1alpha1_generated_Warehouse_UpdateSearchConfig_sync] diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/scripts/fixup_visionai_v1alpha1_keywords.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/scripts/fixup_visionai_v1alpha1_keywords.py new file mode 100644 index 000000000000..0fc9b7e1a292 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/scripts/fixup_visionai_v1alpha1_keywords.py @@ -0,0 +1,263 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 visionaiCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'acquire_lease': ('series', 'owner', 'term', 'lease_type', ), + 'add_application_stream_input': ('name', 'application_stream_inputs', 'request_id', ), + 'clip_asset': ('name', 'temporal_partition', ), + 'create_analysis': ('parent', 'analysis_id', 'analysis', 'request_id', ), + 'create_annotation': ('parent', 'annotation', 'annotation_id', ), + 'create_application': ('parent', 'application_id', 'application', 'request_id', ), + 'create_application_instances': ('name', 'application_instances', 'request_id', ), + 'create_asset': ('parent', 'asset', 'asset_id', ), + 'create_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', ), + 'create_corpus': ('parent', 'corpus', ), + 'create_data_schema': ('parent', 'data_schema', ), + 'create_draft': ('parent', 'draft_id', 'draft', 'request_id', ), + 'create_event': ('parent', 'event_id', 'event', 'request_id', ), + 'create_processor': ('parent', 'processor_id', 'processor', 'request_id', ), + 'create_search_config': ('parent', 'search_config', 'search_config_id', ), + 'create_series': ('parent', 'series_id', 'series', 'request_id', ), + 'create_stream': ('parent', 'stream_id', 'stream', 'request_id', ), + 'delete_analysis': ('name', 'request_id', ), + 'delete_annotation': ('name', ), + 'delete_application': ('name', 'request_id', 'force', ), + 'delete_application_instances': ('name', 'instance_ids', 'request_id', ), + 'delete_asset': ('name', ), + 'delete_cluster': ('name', 'request_id', ), + 'delete_corpus': ('name', ), + 'delete_data_schema': ('name', ), + 'delete_draft': ('name', 'request_id', ), + 'delete_event': ('name', 'request_id', ), + 'delete_processor': ('name', 'request_id', ), + 'delete_search_config': ('name', ), + 'delete_series': ('name', 'request_id', ), + 'delete_stream': ('name', 'request_id', ), + 'deploy_application': ('name', 'validate_only', 'request_id', 'enable_monitoring', ), + 'generate_hls_uri': ('name', 'temporal_partitions', ), + 'generate_stream_hls_token': ('stream', ), + 'get_analysis': ('name', ), + 'get_annotation': ('name', ), + 'get_application': ('name', ), + 'get_asset': ('name', ), + 'get_cluster': ('name', ), + 'get_corpus': ('name', ), + 'get_data_schema': ('name', ), + 'get_draft': ('name', ), + 'get_event': ('name', ), + 'get_instance': ('name', ), + 'get_processor': ('name', ), + 'get_search_config': ('name', ), + 'get_series': ('name', ), + 'get_stream': ('name', ), + 'ingest_asset': ('config', 'time_indexed_data', ), + 'list_analyses': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_annotations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_applications': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_assets': ('parent', 'page_size', 'page_token', ), + 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_corpora': ('parent', 'page_size', 'page_token', ), + 'list_data_schemas': ('parent', 'page_size', 'page_token', ), + 'list_drafts': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_events': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_prebuilt_processors': ('parent', ), + 'list_processors': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_search_configs': ('parent', 'page_size', 'page_token', ), + 'list_series': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_streams': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'materialize_channel': ('parent', 'channel_id', 'channel', 'request_id', ), + 'receive_events': ('setup_request', 'commit_request', ), + 'receive_packets': ('setup_request', 'commit_request', ), + 'release_lease': ('id', 'series', 'owner', ), + 'remove_application_stream_input': ('name', 'target_stream_inputs', 'request_id', ), + 'renew_lease': ('id', 'series', 'owner', 'term', ), + 'search_assets': ('corpus', 'page_size', 'page_token', 'content_time_ranges', 'criteria', 'facet_selections', 'result_annotation_keys', ), + 'send_packets': ('packet', 'metadata', ), + 'undeploy_application': ('name', 'request_id', ), + 'update_analysis': ('update_mask', 'analysis', 'request_id', ), + 'update_annotation': ('annotation', 'update_mask', ), + 'update_application': ('application', 'update_mask', 'request_id', ), + 'update_application_instances': ('name', 'application_instances', 'request_id', 'allow_missing', ), + 'update_application_stream_input': ('name', 'application_stream_inputs', 'request_id', 'allow_missing', ), + 'update_asset': ('asset', 'update_mask', ), + 'update_cluster': ('update_mask', 'cluster', 'request_id', ), + 'update_corpus': ('corpus', 'update_mask', ), + 'update_data_schema': ('data_schema', 'update_mask', ), + 'update_draft': ('draft', 'update_mask', 'request_id', 'allow_missing', ), + 'update_event': ('update_mask', 'event', 'request_id', ), + 'update_processor': ('processor', 'update_mask', 'request_id', ), + 'update_search_config': ('search_config', 'update_mask', ), + 'update_series': ('update_mask', 'series', 'request_id', ), + 'update_stream': ('update_mask', 'stream', 'request_id', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=visionaiCallTransformer(), +): + """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 visionai 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/google-cloud-visionai/v1alpha1/setup.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/setup.py new file mode 100644 index 000000000000..133b5127863d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/setup.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-visionai' + + +description = "Google Cloud Visionai API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/visionai/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-visionai" + +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() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..4cd2782277d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1alpha1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1alpha1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/__init__.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_app_platform.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_app_platform.py new file mode 100644 index 000000000000..5393acc99d02 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_app_platform.py @@ -0,0 +1,21293 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1alpha1.services.app_platform import AppPlatformAsyncClient +from google.cloud.visionai_v1alpha1.services.app_platform import AppPlatformClient +from google.cloud.visionai_v1alpha1.services.app_platform import pagers +from google.cloud.visionai_v1alpha1.services.app_platform import transports +from google.cloud.visionai_v1alpha1.types import annotations +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import platform +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 AppPlatformClient._get_default_mtls_endpoint(None) is None + assert AppPlatformClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AppPlatformClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AppPlatformClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AppPlatformClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AppPlatformClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AppPlatformClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AppPlatformClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AppPlatformClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AppPlatformClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AppPlatformClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AppPlatformClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AppPlatformClient._get_client_cert_source(None, False) is None + assert AppPlatformClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AppPlatformClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AppPlatformClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AppPlatformClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AppPlatformClient._DEFAULT_UNIVERSE + default_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AppPlatformClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AppPlatformClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AppPlatformClient.DEFAULT_MTLS_ENDPOINT + assert AppPlatformClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AppPlatformClient._get_api_endpoint(None, None, default_universe, "always") == AppPlatformClient.DEFAULT_MTLS_ENDPOINT + assert AppPlatformClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AppPlatformClient.DEFAULT_MTLS_ENDPOINT + assert AppPlatformClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AppPlatformClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AppPlatformClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AppPlatformClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AppPlatformClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AppPlatformClient._get_universe_domain(None, None) == AppPlatformClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AppPlatformClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AppPlatformClient, "grpc"), + (AppPlatformAsyncClient, "grpc_asyncio"), + (AppPlatformClient, "rest"), +]) +def test_app_platform_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AppPlatformGrpcTransport, "grpc"), + (transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AppPlatformRestTransport, "rest"), +]) +def test_app_platform_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AppPlatformClient, "grpc"), + (AppPlatformAsyncClient, "grpc_asyncio"), + (AppPlatformClient, "rest"), +]) +def test_app_platform_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_app_platform_client_get_transport_class(): + transport = AppPlatformClient.get_transport_class() + available_transports = [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformRestTransport, + ] + assert transport in available_transports + + transport = AppPlatformClient.get_transport_class("grpc") + assert transport == transports.AppPlatformGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest"), +]) +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +def test_app_platform_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(AppPlatformClient, '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(AppPlatformClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", "true"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", "false"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest", "true"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest", "false"), +]) +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_app_platform_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AppPlatformClient, AppPlatformAsyncClient +]) +@mock.patch.object(AppPlatformClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AppPlatformAsyncClient)) +def test_app_platform_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AppPlatformClient, AppPlatformAsyncClient +]) +@mock.patch.object(AppPlatformClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformClient)) +@mock.patch.object(AppPlatformAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AppPlatformAsyncClient)) +def test_app_platform_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AppPlatformClient._DEFAULT_UNIVERSE + default_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AppPlatformClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc"), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio"), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest"), +]) +def test_app_platform_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", grpc_helpers), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AppPlatformClient, transports.AppPlatformRestTransport, "rest", None), +]) +def test_app_platform_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_app_platform_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1alpha1.services.app_platform.transports.AppPlatformGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AppPlatformClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport, "grpc", grpc_helpers), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_app_platform_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListApplicationsRequest, + dict, +]) +def test_list_applications(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListApplicationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApplicationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_applications_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 = AppPlatformClient( + 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_applications), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_applications() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListApplicationsRequest() + + +def test_list_applications_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListApplicationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_applications(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListApplicationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_applications_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_applications in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_applications] = mock_rpc + request = {} + client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applications(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_applications_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_applications() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListApplicationsRequest() + +@pytest.mark.asyncio +async def test_list_applications_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_applications in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_applications] = mock_object + + request = {} + await client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_applications(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_applications_async(transport: str = 'grpc_asyncio', request_type=platform.ListApplicationsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListApplicationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApplicationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_applications_async_from_dict(): + await test_list_applications_async(request_type=dict) + + +def test_list_applications_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListApplicationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + call.return_value = platform.ListApplicationsResponse() + client.list_applications(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_applications_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListApplicationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse()) + await client.list_applications(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_applications_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListApplicationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_applications( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_applications_flattened_error(): + client = AppPlatformClient( + 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_applications( + platform.ListApplicationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_applications_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListApplicationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListApplicationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_applications( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_applications_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_applications( + platform.ListApplicationsRequest(), + parent='parent_value', + ) + + +def test_list_applications_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_applications(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Application) + for i in results) +def test_list_applications_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + pages = list(client.list_applications(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_applications_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_applications(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Application) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_applications_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applications), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_applications(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.GetApplicationRequest, + dict, +]) +def test_get_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + ) + response = client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Application) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Application.State.CREATED + + +def test_get_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetApplicationRequest() + + +def test_get_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetApplicationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetApplicationRequest( + name='name_value', + ) + +def test_get_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_application] = mock_rpc + request = {} + client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + )) + response = await client.get_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetApplicationRequest() + +@pytest.mark.asyncio +async def test_get_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_application] = mock_object + + request = {} + await client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_application_async(transport: str = 'grpc_asyncio', request_type=platform.GetApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + )) + response = await client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Application) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Application.State.CREATED + + +@pytest.mark.asyncio +async def test_get_application_async_from_dict(): + await test_get_application_async(request_type=dict) + + +def test_get_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value = platform.Application() + client.get_application(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_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Application()) + await client.get_application(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_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Application() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.GetApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Application() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Application()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.GetApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationRequest, + dict, +]) +def test_create_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationRequest() + + +def test_create_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateApplicationRequest( + parent='parent_value', + application_id='application_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationRequest( + parent='parent_value', + application_id='application_id_value', + request_id='request_id_value', + ) + +def test_create_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application] = mock_rpc + request = {} + client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationRequest() + +@pytest.mark.asyncio +async def test_create_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_application] = mock_object + + request = {} + await client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_async(transport: str = 'grpc_asyncio', request_type=platform.CreateApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_application_async_from_dict(): + await test_create_application_async(request_type=dict) + + +def test_create_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_application(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_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_application(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_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_application( + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + + +def test_create_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.CreateApplicationRequest(), + parent='parent_value', + application=platform.Application(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_application( + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.CreateApplicationRequest(), + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationRequest, + dict, +]) +def test_update_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationRequest() + + +def test_update_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateApplicationRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationRequest( + request_id='request_id_value', + ) + +def test_update_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application] = mock_rpc + request = {} + client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationRequest() + +@pytest.mark.asyncio +async def test_update_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_application] = mock_object + + request = {} + await client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_application_async_from_dict(): + await test_update_application_async(request_type=dict) + + +def test_update_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationRequest() + + request.application.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_application(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', + 'application.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationRequest() + + request.application.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_application(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', + 'application.name=name_value', + ) in kw['metadata'] + + +def test_update_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_application( + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.UpdateApplicationRequest(), + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_application( + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].application + mock_val = platform.Application(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.UpdateApplicationRequest(), + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationRequest, + dict, +]) +def test_delete_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_application_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 = AppPlatformClient( + 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_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationRequest() + + +def test_delete_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application] = mock_rpc + request = {} + client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationRequest() + +@pytest.mark.asyncio +async def test_delete_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_application] = mock_object + + request = {} + await client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_application_async_from_dict(): + await test_delete_application_async(request_type=dict) + + +def test_delete_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_application(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_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_application(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_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_application_flattened_error(): + client = AppPlatformClient( + 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_application( + platform.DeleteApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application( + platform.DeleteApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeployApplicationRequest, + dict, +]) +def test_deploy_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_deploy_application_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 = AppPlatformClient( + 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.deploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.deploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeployApplicationRequest() + + +def test_deploy_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.deploy_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_deploy_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.deploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.deploy_application] = mock_rpc + request = {} + client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.deploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_deploy_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.deploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeployApplicationRequest() + +@pytest.mark.asyncio +async def test_deploy_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.deploy_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.deploy_application] = mock_object + + request = {} + await client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.deploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_deploy_application_async(transport: str = 'grpc_asyncio', request_type=platform.DeployApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_deploy_application_async_from_dict(): + await test_deploy_application_async(request_type=dict) + + +def test_deploy_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.deploy_application(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_deploy_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.deploy_application(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_deploy_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.deploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_deploy_application_flattened_error(): + client = AppPlatformClient( + 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.deploy_application( + platform.DeployApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_deploy_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.deploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.deploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_deploy_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.deploy_application( + platform.DeployApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UndeployApplicationRequest, + dict, +]) +def test_undeploy_application(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UndeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_undeploy_application_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 = AppPlatformClient( + 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.undeploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.undeploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UndeployApplicationRequest() + + +def test_undeploy_application_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UndeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.undeploy_application(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UndeployApplicationRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_undeploy_application_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.undeploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undeploy_application] = mock_rpc + request = {} + client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.undeploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_undeploy_application_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.undeploy_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UndeployApplicationRequest() + +@pytest.mark.asyncio +async def test_undeploy_application_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.undeploy_application in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.undeploy_application] = mock_object + + request = {} + await client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.undeploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_undeploy_application_async(transport: str = 'grpc_asyncio', request_type=platform.UndeployApplicationRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UndeployApplicationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_undeploy_application_async_from_dict(): + await test_undeploy_application_async(request_type=dict) + + +def test_undeploy_application_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UndeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.undeploy_application(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_undeploy_application_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UndeployApplicationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.undeploy_application(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_undeploy_application_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.undeploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_undeploy_application_flattened_error(): + client = AppPlatformClient( + 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.undeploy_application( + platform.UndeployApplicationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_undeploy_application_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undeploy_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.undeploy_application( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_undeploy_application_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.undeploy_application( + platform.UndeployApplicationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.AddApplicationStreamInputRequest, + dict, +]) +def test_add_application_stream_input(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.AddApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_application_stream_input_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 = AppPlatformClient( + 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.add_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.AddApplicationStreamInputRequest() + + +def test_add_application_stream_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.AddApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_application_stream_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.AddApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_add_application_stream_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_application_stream_input] = mock_rpc + request = {} + client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_add_application_stream_input_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.add_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.AddApplicationStreamInputRequest() + +@pytest.mark.asyncio +async def test_add_application_stream_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.add_application_stream_input in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.add_application_stream_input] = mock_object + + request = {} + await client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.add_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_add_application_stream_input_async(transport: str = 'grpc_asyncio', request_type=platform.AddApplicationStreamInputRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.AddApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_application_stream_input_async_from_dict(): + await test_add_application_stream_input_async(request_type=dict) + + +def test_add_application_stream_input_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.AddApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_application_stream_input(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_add_application_stream_input_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.AddApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_application_stream_input(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_add_application_stream_input_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_add_application_stream_input_flattened_error(): + client = AppPlatformClient( + 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.add_application_stream_input( + platform.AddApplicationStreamInputRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_add_application_stream_input_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_application_stream_input_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.add_application_stream_input( + platform.AddApplicationStreamInputRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.RemoveApplicationStreamInputRequest, + dict, +]) +def test_remove_application_stream_input(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.RemoveApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_application_stream_input_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 = AppPlatformClient( + 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.remove_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.RemoveApplicationStreamInputRequest() + + +def test_remove_application_stream_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.RemoveApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_application_stream_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.RemoveApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_remove_application_stream_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_application_stream_input] = mock_rpc + request = {} + client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_application_stream_input_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.remove_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.RemoveApplicationStreamInputRequest() + +@pytest.mark.asyncio +async def test_remove_application_stream_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.remove_application_stream_input in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.remove_application_stream_input] = mock_object + + request = {} + await client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.remove_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_application_stream_input_async(transport: str = 'grpc_asyncio', request_type=platform.RemoveApplicationStreamInputRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.RemoveApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_application_stream_input_async_from_dict(): + await test_remove_application_stream_input_async(request_type=dict) + + +def test_remove_application_stream_input_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.RemoveApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_application_stream_input(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_remove_application_stream_input_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.RemoveApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_application_stream_input(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_remove_application_stream_input_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_remove_application_stream_input_flattened_error(): + client = AppPlatformClient( + 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.remove_application_stream_input( + platform.RemoveApplicationStreamInputRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_remove_application_stream_input_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_application_stream_input_flattened_error_async(): + client = AppPlatformAsyncClient( + 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.remove_application_stream_input( + platform.RemoveApplicationStreamInputRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationStreamInputRequest, + dict, +]) +def test_update_application_stream_input(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_application_stream_input_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 = AppPlatformClient( + 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_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationStreamInputRequest() + + +def test_update_application_stream_input_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_stream_input(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationStreamInputRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_update_application_stream_input_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_stream_input] = mock_rpc + request = {} + client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_stream_input_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_stream_input() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationStreamInputRequest() + +@pytest.mark.asyncio +async def test_update_application_stream_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_application_stream_input in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_application_stream_input] = mock_object + + request = {} + await client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_stream_input_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateApplicationStreamInputRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationStreamInputRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_application_stream_input_async_from_dict(): + await test_update_application_stream_input_async(request_type=dict) + + +def test_update_application_stream_input_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_application_stream_input(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_application_stream_input_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationStreamInputRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_application_stream_input(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_application_stream_input_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_update_application_stream_input_flattened_error(): + client = AppPlatformClient( + 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_application_stream_input( + platform.UpdateApplicationStreamInputRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_update_application_stream_input_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_stream_input), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_application_stream_input( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_application_stream_input_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_stream_input( + platform.UpdateApplicationStreamInputRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListInstancesRequest, + dict, +]) +def test_list_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_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 = AppPlatformClient( + 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_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListInstancesRequest() + + +def test_list_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListInstancesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListInstancesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListInstancesRequest() + +@pytest.mark.asyncio +async def test_list_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_instances] = mock_object + + request = {} + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_instances_async(transport: str = 'grpc_asyncio', request_type=platform.ListInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = platform.ListInstancesResponse() + client.list_instances(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_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse()) + await client.list_instances(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_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_instances_flattened_error(): + client = AppPlatformClient( + 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_instances( + platform.ListInstancesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListInstancesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_instances( + platform.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instances(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Instance) + for i in results) +def test_list_instances_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(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_instances_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Instance) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_instances(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.GetInstanceRequest, + dict, +]) +def test_get_instance(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Instance.State.CREATING, + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Instance.State.CREATING + + +def test_get_instance_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 = AppPlatformClient( + 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_instance), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetInstanceRequest() + + +def test_get_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetInstanceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetInstanceRequest( + name='name_value', + ) + +def test_get_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_instance_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Instance.State.CREATING, + )) + response = await client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetInstanceRequest() + +@pytest.mark.asyncio +async def test_get_instance_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_instance in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_instance] = mock_object + + request = {} + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=platform.GetInstanceRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Instance.State.CREATING, + )) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Instance.State.CREATING + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = platform.Instance() + client.get_instance(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_instance_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance()) + await client.get_instance(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_instance_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_instance_flattened_error(): + client = AppPlatformClient( + 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_instance( + platform.GetInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_instance_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_instance( + platform.GetInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationInstancesRequest, + dict, +]) +def test_create_application_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_application_instances_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 = AppPlatformClient( + 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_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationInstancesRequest() + + +def test_create_application_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_application_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_create_application_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application_instances] = mock_rpc + request = {} + client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateApplicationInstancesRequest() + +@pytest.mark.asyncio +async def test_create_application_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_application_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_application_instances] = mock_object + + request = {} + await client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_application_instances_async(transport: str = 'grpc_asyncio', request_type=platform.CreateApplicationInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_application_instances_async_from_dict(): + await test_create_application_instances_async(request_type=dict) + + +def test_create_application_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_application_instances(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_create_application_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_application_instances(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_create_application_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_create_application_instances_flattened_error(): + client = AppPlatformClient( + 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_application_instances( + platform.CreateApplicationInstancesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_create_application_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_application_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_instances( + platform.CreateApplicationInstancesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationInstancesRequest, + dict, +]) +def test_delete_application_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_application_instances_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 = AppPlatformClient( + 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_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationInstancesRequest() + + +def test_delete_application_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_application_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_application_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application_instances] = mock_rpc + request = {} + client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteApplicationInstancesRequest() + +@pytest.mark.asyncio +async def test_delete_application_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_application_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_application_instances] = mock_object + + request = {} + await client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_application_instances_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteApplicationInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_application_instances_async_from_dict(): + await test_delete_application_instances_async(request_type=dict) + + +def test_delete_application_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_application_instances(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_application_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_application_instances(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_application_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_application_instances_flattened_error(): + client = AppPlatformClient( + 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_application_instances( + platform.DeleteApplicationInstancesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_application_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_application_instances( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_application_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_instances( + platform.DeleteApplicationInstancesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationInstancesRequest, + dict, +]) +def test_update_application_instances(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_application_instances_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 = AppPlatformClient( + 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_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationInstancesRequest() + + +def test_update_application_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_application_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationInstancesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_update_application_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_instances] = mock_rpc + request = {} + client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_instances_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateApplicationInstancesRequest() + +@pytest.mark.asyncio +async def test_update_application_instances_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_application_instances in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_application_instances] = mock_object + + request = {} + await client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_application_instances_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateApplicationInstancesRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateApplicationInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_application_instances_async_from_dict(): + await test_update_application_instances_async(request_type=dict) + + +def test_update_application_instances_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_application_instances(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_application_instances_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateApplicationInstancesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_application_instances(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_application_instances_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_application_instances( + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].application_instances + mock_val = [platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))] + assert arg == mock_val + + +def test_update_application_instances_flattened_error(): + client = AppPlatformClient( + 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_application_instances( + platform.UpdateApplicationInstancesRequest(), + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + +@pytest.mark.asyncio +async def test_update_application_instances_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_application_instances( + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].application_instances + mock_val = [platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_application_instances_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_application_instances( + platform.UpdateApplicationInstancesRequest(), + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListDraftsRequest, + dict, +]) +def test_list_drafts(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListDraftsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDraftsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_drafts_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 = AppPlatformClient( + 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_drafts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_drafts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListDraftsRequest() + + +def test_list_drafts_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListDraftsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_drafts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListDraftsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_drafts_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_drafts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_drafts] = mock_rpc + request = {} + client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_drafts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_drafts_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_drafts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListDraftsRequest() + +@pytest.mark.asyncio +async def test_list_drafts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_drafts in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_drafts] = mock_object + + request = {} + await client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_drafts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_drafts_async(transport: str = 'grpc_asyncio', request_type=platform.ListDraftsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListDraftsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDraftsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_drafts_async_from_dict(): + await test_list_drafts_async(request_type=dict) + + +def test_list_drafts_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListDraftsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + call.return_value = platform.ListDraftsResponse() + client.list_drafts(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_drafts_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListDraftsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse()) + await client.list_drafts(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_drafts_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListDraftsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_drafts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_drafts_flattened_error(): + client = AppPlatformClient( + 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_drafts( + platform.ListDraftsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_drafts_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListDraftsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListDraftsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_drafts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_drafts_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_drafts( + platform.ListDraftsRequest(), + parent='parent_value', + ) + + +def test_list_drafts_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_drafts(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Draft) + for i in results) +def test_list_drafts_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + pages = list(client.list_drafts(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_drafts_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_drafts(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Draft) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_drafts_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_drafts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_drafts(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.GetDraftRequest, + dict, +]) +def test_get_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Draft) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetDraftRequest() + + +def test_get_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetDraftRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetDraftRequest( + name='name_value', + ) + +def test_get_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_draft] = mock_rpc + request = {} + client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetDraftRequest() + +@pytest.mark.asyncio +async def test_get_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_draft] = mock_object + + request = {} + await client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_draft_async(transport: str = 'grpc_asyncio', request_type=platform.GetDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Draft) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_draft_async_from_dict(): + await test_get_draft_async(request_type=dict) + + +def test_get_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + call.return_value = platform.Draft() + client.get_draft(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_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft()) + await client.get_draft(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_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Draft() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.GetDraftRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Draft() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Draft()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.GetDraftRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateDraftRequest, + dict, +]) +def test_create_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateDraftRequest() + + +def test_create_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateDraftRequest( + parent='parent_value', + draft_id='draft_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateDraftRequest( + parent='parent_value', + draft_id='draft_id_value', + request_id='request_id_value', + ) + +def test_create_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_draft] = mock_rpc + request = {} + client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateDraftRequest() + +@pytest.mark.asyncio +async def test_create_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_draft] = mock_object + + request = {} + await client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_draft_async(transport: str = 'grpc_asyncio', request_type=platform.CreateDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_draft_async_from_dict(): + await test_create_draft_async(request_type=dict) + + +def test_create_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateDraftRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_draft(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_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateDraftRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_draft(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_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_draft( + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].draft_id + mock_val = 'draft_id_value' + assert arg == mock_val + + +def test_create_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.CreateDraftRequest(), + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + +@pytest.mark.asyncio +async def test_create_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_draft( + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].draft_id + mock_val = 'draft_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.CreateDraftRequest(), + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateDraftRequest, + dict, +]) +def test_update_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateDraftRequest() + + +def test_update_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateDraftRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateDraftRequest( + request_id='request_id_value', + ) + +def test_update_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_draft] = mock_rpc + request = {} + client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateDraftRequest() + +@pytest.mark.asyncio +async def test_update_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_draft] = mock_object + + request = {} + await client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_draft_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_draft_async_from_dict(): + await test_update_draft_async(request_type=dict) + + +def test_update_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateDraftRequest() + + request.draft.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_draft(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', + 'draft.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateDraftRequest() + + request.draft.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_draft(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', + 'draft.name=name_value', + ) in kw['metadata'] + + +def test_update_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_draft( + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.UpdateDraftRequest(), + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_draft( + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].draft + mock_val = platform.Draft(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.UpdateDraftRequest(), + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteDraftRequest, + dict, +]) +def test_delete_draft(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_draft_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 = AppPlatformClient( + 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_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteDraftRequest() + + +def test_delete_draft_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteDraftRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_draft(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteDraftRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_draft_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_draft] = mock_rpc + request = {} + client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_draft_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_draft() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteDraftRequest() + +@pytest.mark.asyncio +async def test_delete_draft_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_draft in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_draft] = mock_object + + request = {} + await client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_draft_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteDraftRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteDraftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_draft_async_from_dict(): + await test_delete_draft_async(request_type=dict) + + +def test_delete_draft_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_draft(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_draft_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteDraftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_draft(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_draft_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_draft_flattened_error(): + client = AppPlatformClient( + 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_draft( + platform.DeleteDraftRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_draft_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_draft), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_draft( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_draft_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_draft( + platform.DeleteDraftRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListProcessorsRequest, + dict, +]) +def test_list_processors(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_processors_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 = AppPlatformClient( + 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_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListProcessorsRequest() + + +def test_list_processors_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListProcessorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_processors(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListProcessorsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_processors_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_processors] = mock_rpc + request = {} + client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_processors_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListProcessorsRequest() + +@pytest.mark.asyncio +async def test_list_processors_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_processors in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_processors] = mock_object + + request = {} + await client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_processors_async(transport: str = 'grpc_asyncio', request_type=platform.ListProcessorsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_processors_async_from_dict(): + await test_list_processors_async(request_type=dict) + + +def test_list_processors_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = platform.ListProcessorsResponse() + client.list_processors(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_processors_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse()) + await client.list_processors(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_processors_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListProcessorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_processors_flattened_error(): + client = AppPlatformClient( + 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_processors( + platform.ListProcessorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_processors_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListProcessorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListProcessorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_processors_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processors( + platform.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_pager(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_processors(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Processor) + for i in results) +def test_list_processors_pages(transport_name: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + pages = list(client.list_processors(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_processors_async_pager(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_processors(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, platform.Processor) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_processors_async_pages(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_processors), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_processors(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + platform.ListPrebuiltProcessorsRequest, + dict, +]) +def test_list_prebuilt_processors(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListPrebuiltProcessorsResponse( + ) + response = client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.ListPrebuiltProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.ListPrebuiltProcessorsResponse) + + +def test_list_prebuilt_processors_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 = AppPlatformClient( + 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_prebuilt_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_prebuilt_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListPrebuiltProcessorsRequest() + + +def test_list_prebuilt_processors_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.ListPrebuiltProcessorsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_prebuilt_processors(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListPrebuiltProcessorsRequest( + parent='parent_value', + ) + +def test_list_prebuilt_processors_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_prebuilt_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_prebuilt_processors] = mock_rpc + request = {} + client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_prebuilt_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse( + )) + response = await client.list_prebuilt_processors() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.ListPrebuiltProcessorsRequest() + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_prebuilt_processors in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_prebuilt_processors] = mock_object + + request = {} + await client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_prebuilt_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_async(transport: str = 'grpc_asyncio', request_type=platform.ListPrebuiltProcessorsRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse( + )) + response = await client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.ListPrebuiltProcessorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.ListPrebuiltProcessorsResponse) + + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_async_from_dict(): + await test_list_prebuilt_processors_async(request_type=dict) + + +def test_list_prebuilt_processors_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListPrebuiltProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + call.return_value = platform.ListPrebuiltProcessorsResponse() + client.list_prebuilt_processors(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_prebuilt_processors_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.ListPrebuiltProcessorsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse()) + await client.list_prebuilt_processors(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_prebuilt_processors_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListPrebuiltProcessorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_prebuilt_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_prebuilt_processors_flattened_error(): + client = AppPlatformClient( + 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_prebuilt_processors( + platform.ListPrebuiltProcessorsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prebuilt_processors), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.ListPrebuiltProcessorsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.ListPrebuiltProcessorsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_prebuilt_processors( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_prebuilt_processors_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_prebuilt_processors( + platform.ListPrebuiltProcessorsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.GetProcessorRequest, + dict, +]) +def test_get_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + ) + response = client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.GetProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Processor) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.processor_type == platform.Processor.ProcessorType.PRETRAINED + assert response.model_type == platform.ModelType.IMAGE_CLASSIFICATION + assert response.state == platform.Processor.ProcessorState.CREATING + assert response.configuration_typeurl == 'configuration_typeurl_value' + assert response.supported_annotation_types == [annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE] + assert response.supports_post_processing is True + + +def test_get_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetProcessorRequest() + + +def test_get_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.GetProcessorRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetProcessorRequest( + name='name_value', + ) + +def test_get_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_processor] = mock_rpc + request = {} + client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + )) + response = await client.get_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.GetProcessorRequest() + +@pytest.mark.asyncio +async def test_get_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_processor] = mock_object + + request = {} + await client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_processor_async(transport: str = 'grpc_asyncio', request_type=platform.GetProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + )) + response = await client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.GetProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Processor) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.processor_type == platform.Processor.ProcessorType.PRETRAINED + assert response.model_type == platform.ModelType.IMAGE_CLASSIFICATION + assert response.state == platform.Processor.ProcessorState.CREATING + assert response.configuration_typeurl == 'configuration_typeurl_value' + assert response.supported_annotation_types == [annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE] + assert response.supports_post_processing is True + + +@pytest.mark.asyncio +async def test_get_processor_async_from_dict(): + await test_get_processor_async(request_type=dict) + + +def test_get_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = platform.Processor() + client.get_processor(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_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.GetProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor()) + await client.get_processor(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_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Processor() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.GetProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = platform.Processor() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(platform.Processor()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.GetProcessorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateProcessorRequest, + dict, +]) +def test_create_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.CreateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateProcessorRequest() + + +def test_create_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.CreateProcessorRequest( + parent='parent_value', + processor_id='processor_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateProcessorRequest( + parent='parent_value', + processor_id='processor_id_value', + request_id='request_id_value', + ) + +def test_create_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_processor] = mock_rpc + request = {} + client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.CreateProcessorRequest() + +@pytest.mark.asyncio +async def test_create_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_processor] = mock_object + + request = {} + await client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_processor_async(transport: str = 'grpc_asyncio', request_type=platform.CreateProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.CreateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_processor_async_from_dict(): + await test_create_processor_async(request_type=dict) + + +def test_create_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_processor(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_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.CreateProcessorRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_processor(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_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_processor( + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].processor_id + mock_val = 'processor_id_value' + assert arg == mock_val + + +def test_create_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.CreateProcessorRequest(), + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + +@pytest.mark.asyncio +async def test_create_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_processor( + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].processor_id + mock_val = 'processor_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.CreateProcessorRequest(), + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateProcessorRequest, + dict, +]) +def test_update_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.UpdateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateProcessorRequest() + + +def test_update_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.UpdateProcessorRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateProcessorRequest( + request_id='request_id_value', + ) + +def test_update_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_processor] = mock_rpc + request = {} + client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.UpdateProcessorRequest() + +@pytest.mark.asyncio +async def test_update_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_processor] = mock_object + + request = {} + await client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_processor_async(transport: str = 'grpc_asyncio', request_type=platform.UpdateProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.UpdateProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_processor_async_from_dict(): + await test_update_processor_async(request_type=dict) + + +def test_update_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateProcessorRequest() + + request.processor.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_processor(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', + 'processor.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.UpdateProcessorRequest() + + request.processor.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_processor(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', + 'processor.name=name_value', + ) in kw['metadata'] + + +def test_update_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_processor( + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.UpdateProcessorRequest(), + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_processor( + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].processor + mock_val = platform.Processor(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.UpdateProcessorRequest(), + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteProcessorRequest, + dict, +]) +def test_delete_processor(request_type, transport: str = 'grpc'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = platform.DeleteProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_processor_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 = AppPlatformClient( + 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_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteProcessorRequest() + + +def test_delete_processor_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = platform.DeleteProcessorRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_processor(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteProcessorRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_processor_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_processor] = mock_rpc + request = {} + client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_processor_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_processor() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == platform.DeleteProcessorRequest() + +@pytest.mark.asyncio +async def test_delete_processor_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_processor in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_processor] = mock_object + + request = {} + await client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_processor_async(transport: str = 'grpc_asyncio', request_type=platform.DeleteProcessorRequest): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = platform.DeleteProcessorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_processor_async_from_dict(): + await test_delete_processor_async(request_type=dict) + + +def test_delete_processor_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_processor(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_processor_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = platform.DeleteProcessorRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_processor(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_processor_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_processor_flattened_error(): + client = AppPlatformClient( + 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_processor( + platform.DeleteProcessorRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_processor_flattened_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_processor), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_processor( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_processor_flattened_error_async(): + client = AppPlatformAsyncClient( + 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_processor( + platform.DeleteProcessorRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListApplicationsRequest, + dict, +]) +def test_list_applications_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListApplicationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListApplicationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_applications(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApplicationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_applications_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_applications in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_applications] = mock_rpc + + request = {} + client.list_applications(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applications(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_applications_rest_required_fields(request_type=platform.ListApplicationsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_applications._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_applications._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListApplicationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListApplicationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_applications(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_applications_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_applications._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_applications_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_applications") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_applications") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListApplicationsRequest.pb(platform.ListApplicationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListApplicationsResponse.to_json(platform.ListApplicationsResponse()) + + request = platform.ListApplicationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListApplicationsResponse() + + client.list_applications(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_applications_rest_bad_request(transport: str = 'rest', request_type=platform.ListApplicationsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_applications(request) + + +def test_list_applications_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListApplicationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListApplicationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_applications(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/applications" % client.transport._host, args[1]) + + +def test_list_applications_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_applications( + platform.ListApplicationsRequest(), + parent='parent_value', + ) + + +def test_list_applications_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + platform.Application(), + ], + next_page_token='abc', + ), + platform.ListApplicationsResponse( + applications=[], + next_page_token='def', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + ], + next_page_token='ghi', + ), + platform.ListApplicationsResponse( + applications=[ + platform.Application(), + platform.Application(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListApplicationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_applications(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Application) + for i in results) + + pages = list(client.list_applications(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.GetApplicationRequest, + dict, +]) +def test_get_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Application( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Application.State.CREATED, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Application.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_application(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Application) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Application.State.CREATED + +def test_get_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_application] = mock_rpc + + request = {} + client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_application_rest_required_fields(request_type=platform.GetApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Application() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Application.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetApplicationRequest.pb(platform.GetApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Application.to_json(platform.Application()) + + request = platform.GetApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Application() + + client.get_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_application_rest_bad_request(transport: str = 'rest', request_type=platform.GetApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_application(request) + + +def test_get_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Application() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Application.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}" % client.transport._host, args[1]) + + +def test_get_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_application( + platform.GetApplicationRequest(), + name='name_value', + ) + + +def test_get_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationRequest, + dict, +]) +def test_create_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["application"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}, 'runtime_info': {'deploy_time': {}, 'global_output_resources': [{'output_resource': 'output_resource_value', 'producer_node': 'producer_node_value', 'key': 'key_value'}], 'monitoring_config': {'enabled': True}}, 'state': 1} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.CreateApplicationRequest.meta.fields["application"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["application"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["application"][field])): + del request_init["application"][field][i][subfield] + else: + del request_init["application"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application] = mock_rpc + + request = {} + client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_application_rest_required_fields(request_type=platform.CreateApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["application_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "applicationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "applicationId" in jsonified_request + assert jsonified_request["applicationId"] == request_init["application_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["applicationId"] = 'application_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("application_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "applicationId" in jsonified_request + assert jsonified_request["applicationId"] == 'application_id_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_application(request) + + expected_params = [ + ( + "applicationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(("applicationId", "requestId", )) & set(("parent", "applicationId", "application", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateApplicationRequest.pb(platform.CreateApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_application_rest_bad_request(transport: str = 'rest', request_type=platform.CreateApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_application(request) + + +def test_create_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + application=platform.Application(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/applications" % client.transport._host, args[1]) + + +def test_create_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_application( + platform.CreateApplicationRequest(), + parent='parent_value', + application=platform.Application(name='name_value'), + ) + + +def test_create_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationRequest, + dict, +]) +def test_update_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'application': {'name': 'projects/sample1/locations/sample2/applications/sample3'}} + request_init["application"] = {'name': 'projects/sample1/locations/sample2/applications/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}, 'runtime_info': {'deploy_time': {}, 'global_output_resources': [{'output_resource': 'output_resource_value', 'producer_node': 'producer_node_value', 'key': 'key_value'}], 'monitoring_config': {'enabled': True}}, 'state': 1} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.UpdateApplicationRequest.meta.fields["application"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["application"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["application"][field])): + del request_init["application"][field][i][subfield] + else: + del request_init["application"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application] = mock_rpc + + request = {} + client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_application_rest_required_fields(request_type=platform.UpdateApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("application", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateApplicationRequest.pb(platform.UpdateApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_application_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'application': {'name': 'projects/sample1/locations/sample2/applications/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_application(request) + + +def test_update_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'application': {'name': 'projects/sample1/locations/sample2/applications/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{application.name=projects/*/locations/*/applications/*}" % client.transport._host, args[1]) + + +def test_update_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_application( + platform.UpdateApplicationRequest(), + application=platform.Application(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationRequest, + dict, +]) +def test_delete_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application] = mock_rpc + + request = {} + client.delete_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_application_rest_required_fields(request_type=platform.DeleteApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", "requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteApplicationRequest.pb(platform.DeleteApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_application_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_application(request) + + +def test_delete_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}" % client.transport._host, args[1]) + + +def test_delete_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_application( + platform.DeleteApplicationRequest(), + name='name_value', + ) + + +def test_delete_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeployApplicationRequest, + dict, +]) +def test_deploy_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.deploy_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_deploy_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.deploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.deploy_application] = mock_rpc + + request = {} + client.deploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.deploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_deploy_application_rest_required_fields(request_type=platform.DeployApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.deploy_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_deploy_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.deploy_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_deploy_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_deploy_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_deploy_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeployApplicationRequest.pb(platform.DeployApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeployApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.deploy_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_deploy_application_rest_bad_request(transport: str = 'rest', request_type=platform.DeployApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.deploy_application(request) + + +def test_deploy_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.deploy_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:deploy" % client.transport._host, args[1]) + + +def test_deploy_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.deploy_application( + platform.DeployApplicationRequest(), + name='name_value', + ) + + +def test_deploy_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UndeployApplicationRequest, + dict, +]) +def test_undeploy_application_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.undeploy_application(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_undeploy_application_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.undeploy_application in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.undeploy_application] = mock_rpc + + request = {} + client.undeploy_application(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.undeploy_application(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_undeploy_application_rest_required_fields(request_type=platform.UndeployApplicationRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_application._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.undeploy_application(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undeploy_application_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undeploy_application._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undeploy_application_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_undeploy_application") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_undeploy_application") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UndeployApplicationRequest.pb(platform.UndeployApplicationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UndeployApplicationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undeploy_application(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undeploy_application_rest_bad_request(transport: str = 'rest', request_type=platform.UndeployApplicationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undeploy_application(request) + + +def test_undeploy_application_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.undeploy_application(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:undeploy" % client.transport._host, args[1]) + + +def test_undeploy_application_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undeploy_application( + platform.UndeployApplicationRequest(), + name='name_value', + ) + + +def test_undeploy_application_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.AddApplicationStreamInputRequest, + dict, +]) +def test_add_application_stream_input_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.add_application_stream_input(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_add_application_stream_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_application_stream_input] = mock_rpc + + request = {} + client.add_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_add_application_stream_input_rest_required_fields(request_type=platform.AddApplicationStreamInputRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.add_application_stream_input(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_add_application_stream_input_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.add_application_stream_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_application_stream_input_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_add_application_stream_input") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_add_application_stream_input") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.AddApplicationStreamInputRequest.pb(platform.AddApplicationStreamInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.AddApplicationStreamInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.add_application_stream_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_application_stream_input_rest_bad_request(transport: str = 'rest', request_type=platform.AddApplicationStreamInputRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.add_application_stream_input(request) + + +def test_add_application_stream_input_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.add_application_stream_input(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:addStreamInput" % client.transport._host, args[1]) + + +def test_add_application_stream_input_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_application_stream_input( + platform.AddApplicationStreamInputRequest(), + name='name_value', + ) + + +def test_add_application_stream_input_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.RemoveApplicationStreamInputRequest, + dict, +]) +def test_remove_application_stream_input_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.remove_application_stream_input(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_remove_application_stream_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_application_stream_input] = mock_rpc + + request = {} + client.remove_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_application_stream_input_rest_required_fields(request_type=platform.RemoveApplicationStreamInputRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.remove_application_stream_input(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_application_stream_input_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_application_stream_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_application_stream_input_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_remove_application_stream_input") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_remove_application_stream_input") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.RemoveApplicationStreamInputRequest.pb(platform.RemoveApplicationStreamInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.RemoveApplicationStreamInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.remove_application_stream_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_application_stream_input_rest_bad_request(transport: str = 'rest', request_type=platform.RemoveApplicationStreamInputRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.remove_application_stream_input(request) + + +def test_remove_application_stream_input_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.remove_application_stream_input(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:removeStreamInput" % client.transport._host, args[1]) + + +def test_remove_application_stream_input_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_application_stream_input( + platform.RemoveApplicationStreamInputRequest(), + name='name_value', + ) + + +def test_remove_application_stream_input_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationStreamInputRequest, + dict, +]) +def test_update_application_stream_input_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_application_stream_input(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_application_stream_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_stream_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_stream_input] = mock_rpc + + request = {} + client.update_application_stream_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_stream_input(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_application_stream_input_rest_required_fields(request_type=platform.UpdateApplicationStreamInputRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_stream_input._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_application_stream_input(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_application_stream_input_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_application_stream_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_application_stream_input_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_application_stream_input") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_application_stream_input") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateApplicationStreamInputRequest.pb(platform.UpdateApplicationStreamInputRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateApplicationStreamInputRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_application_stream_input(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_application_stream_input_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateApplicationStreamInputRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_application_stream_input(request) + + +def test_update_application_stream_input_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_application_stream_input(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:updateStreamInput" % client.transport._host, args[1]) + + +def test_update_application_stream_input_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_application_stream_input( + platform.UpdateApplicationStreamInputRequest(), + name='name_value', + ) + + +def test_update_application_stream_input_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListInstancesRequest, + dict, +]) +def test_list_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_instances_rest_required_fields(request_type=platform.ListInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListInstancesRequest.pb(platform.ListInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListInstancesResponse.to_json(platform.ListInstancesResponse()) + + request = platform.ListInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListInstancesResponse() + + client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_instances_rest_bad_request(transport: str = 'rest', request_type=platform.ListInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_instances(request) + + +def test_list_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/applications/*}/instances" % client.transport._host, args[1]) + + +def test_list_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instances( + platform.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + platform.Instance(), + ], + next_page_token='abc', + ), + platform.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + ], + next_page_token='ghi', + ), + platform.ListInstancesResponse( + instances=[ + platform.Instance(), + platform.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListInstancesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Instance) + for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.GetInstanceRequest, + dict, +]) +def test_get_instance_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/instances/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Instance( + name='name_value', + display_name='display_name_value', + description='description_value', + state=platform.Instance.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == platform.Instance.State.CREATING + +def test_get_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_instance_rest_required_fields(request_type=platform.GetInstanceRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetInstanceRequest.pb(platform.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Instance.to_json(platform.Instance()) + + request = platform.GetInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Instance() + + client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(transport: str = 'rest', request_type=platform.GetInstanceRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/instances/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_instance(request) + + +def test_get_instance_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3/instances/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*/instances/*}" % client.transport._host, args[1]) + + +def test_get_instance_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + platform.GetInstanceRequest(), + name='name_value', + ) + + +def test_get_instance_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateApplicationInstancesRequest, + dict, +]) +def test_create_application_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_application_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_application_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_application_instances] = mock_rpc + + request = {} + client.create_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_application_instances_rest_required_fields(request_type=platform.CreateApplicationInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_application_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_application_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_application_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "applicationInstances", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_application_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_application_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_application_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateApplicationInstancesRequest.pb(platform.CreateApplicationInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateApplicationInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_application_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_application_instances_rest_bad_request(transport: str = 'rest', request_type=platform.CreateApplicationInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_application_instances(request) + + +def test_create_application_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_application_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:createApplicationInstances" % client.transport._host, args[1]) + + +def test_create_application_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_application_instances( + platform.CreateApplicationInstancesRequest(), + name='name_value', + ) + + +def test_create_application_instances_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteApplicationInstancesRequest, + dict, +]) +def test_delete_application_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_application_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_application_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_application_instances] = mock_rpc + + request = {} + client.delete_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_application_instances_rest_required_fields(request_type=platform.DeleteApplicationInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request_init["instance_ids"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["instanceIds"] = 'instance_ids_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "instanceIds" in jsonified_request + assert jsonified_request["instanceIds"] == 'instance_ids_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_application_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_application_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_application_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "instanceIds", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_application_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_application_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_application_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteApplicationInstancesRequest.pb(platform.DeleteApplicationInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteApplicationInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_application_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_application_instances_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteApplicationInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_application_instances(request) + + +def test_delete_application_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_application_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:deleteApplicationInstances" % client.transport._host, args[1]) + + +def test_delete_application_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_application_instances( + platform.DeleteApplicationInstancesRequest(), + name='name_value', + ) + + +def test_delete_application_instances_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateApplicationInstancesRequest, + dict, +]) +def test_update_application_instances_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_application_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_application_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_application_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_application_instances] = mock_rpc + + request = {} + client.update_application_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_application_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_application_instances_rest_required_fields(request_type=platform.UpdateApplicationInstancesRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_application_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_application_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_application_instances_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_application_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_application_instances_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_application_instances") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_application_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateApplicationInstancesRequest.pb(platform.UpdateApplicationInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateApplicationInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_application_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_application_instances_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateApplicationInstancesRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_application_instances(request) + + +def test_update_application_instances_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_application_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*}:updateApplicationInstances" % client.transport._host, args[1]) + + +def test_update_application_instances_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_application_instances( + platform.UpdateApplicationInstancesRequest(), + name='name_value', + application_instances=[platform.UpdateApplicationInstancesRequest.UpdateApplicationInstance(update_mask=field_mask_pb2.FieldMask(paths=['paths_value']))], + ) + + +def test_update_application_instances_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListDraftsRequest, + dict, +]) +def test_list_drafts_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListDraftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListDraftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_drafts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDraftsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_drafts_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_drafts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_drafts] = mock_rpc + + request = {} + client.list_drafts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_drafts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_drafts_rest_required_fields(request_type=platform.ListDraftsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_drafts._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_drafts._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListDraftsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListDraftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_drafts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_drafts_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_drafts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_drafts_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_drafts") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_drafts") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListDraftsRequest.pb(platform.ListDraftsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListDraftsResponse.to_json(platform.ListDraftsResponse()) + + request = platform.ListDraftsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListDraftsResponse() + + client.list_drafts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_drafts_rest_bad_request(transport: str = 'rest', request_type=platform.ListDraftsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_drafts(request) + + +def test_list_drafts_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListDraftsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListDraftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_drafts(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/applications/*}/drafts" % client.transport._host, args[1]) + + +def test_list_drafts_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_drafts( + platform.ListDraftsRequest(), + parent='parent_value', + ) + + +def test_list_drafts_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + platform.Draft(), + ], + next_page_token='abc', + ), + platform.ListDraftsResponse( + drafts=[], + next_page_token='def', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + ], + next_page_token='ghi', + ), + platform.ListDraftsResponse( + drafts=[ + platform.Draft(), + platform.Draft(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListDraftsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + pager = client.list_drafts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Draft) + for i in results) + + pages = list(client.list_drafts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.GetDraftRequest, + dict, +]) +def test_get_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Draft( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Draft.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_draft(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Draft) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_draft] = mock_rpc + + request = {} + client.get_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_draft_rest_required_fields(request_type=platform.GetDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Draft() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Draft.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_draft(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetDraftRequest.pb(platform.GetDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Draft.to_json(platform.Draft()) + + request = platform.GetDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Draft() + + client.get_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_draft_rest_bad_request(transport: str = 'rest', request_type=platform.GetDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_draft(request) + + +def test_get_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Draft() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Draft.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*/drafts/*}" % client.transport._host, args[1]) + + +def test_get_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_draft( + platform.GetDraftRequest(), + name='name_value', + ) + + +def test_get_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateDraftRequest, + dict, +]) +def test_create_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request_init["draft"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'draft_application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.CreateDraftRequest.meta.fields["draft"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["draft"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["draft"][field])): + del request_init["draft"][field][i][subfield] + else: + del request_init["draft"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_draft(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_draft] = mock_rpc + + request = {} + client.create_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_draft_rest_required_fields(request_type=platform.CreateDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["draft_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "draftId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "draftId" in jsonified_request + assert jsonified_request["draftId"] == request_init["draft_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["draftId"] = 'draft_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_draft._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("draft_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "draftId" in jsonified_request + assert jsonified_request["draftId"] == 'draft_id_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_draft(request) + + expected_params = [ + ( + "draftId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(("draftId", "requestId", )) & set(("parent", "draftId", "draft", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateDraftRequest.pb(platform.CreateDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_draft_rest_bad_request(transport: str = 'rest', request_type=platform.CreateDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_draft(request) + + +def test_create_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/applications/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/applications/*}/drafts" % client.transport._host, args[1]) + + +def test_create_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_draft( + platform.CreateDraftRequest(), + parent='parent_value', + draft=platform.Draft(name='name_value'), + draft_id='draft_id_value', + ) + + +def test_create_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateDraftRequest, + dict, +]) +def test_update_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'draft': {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'}} + request_init["draft"] = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'draft_application_configs': {'nodes': [{'output_all_output_channels_to_stream': True, 'name': 'name_value', 'display_name': 'display_name_value', 'node_config': {'video_stream_input_config': {'streams': ['streams_value1', 'streams_value2'], 'streams_with_annotation': [{'stream': 'stream_value', 'application_annotations': [{'active_zone': {'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}, 'crossing_line': {'normalized_vertices': {}}, 'id': 'id_value', 'display_name': 'display_name_value', 'source_stream': 'source_stream_value', 'type_': 1}], 'node_annotations': [{'node': 'node_value', 'annotations': {}}]}]}, 'ai_enabled_devices_input_config': {}, 'media_warehouse_config': {'corpus': 'corpus_value', 'region': 'region_value', 'ttl': {'seconds': 751, 'nanos': 543}}, 'person_blur_config': {'person_blur_type': 1, 'faces_only': True}, 'occupancy_count_config': {'enable_people_counting': True, 'enable_vehicle_counting': True, 'enable_dwelling_time_tracking': True}, 'person_vehicle_detection_config': {'enable_people_counting': True, 'enable_vehicle_counting': True}, 'vertex_automl_vision_config': {'confidence_threshold': 0.2106, 'max_predictions': 1609}, 'vertex_automl_video_config': {'confidence_threshold': 0.2106, 'blocked_labels': ['blocked_labels_value1', 'blocked_labels_value2'], 'max_predictions': 1609, 'bounding_box_size_limit': 0.2454}, 'vertex_custom_config': {'max_prediction_fps': 1918, 'dedicated_resources': {'machine_spec': {'machine_type': 'machine_type_value', 'accelerator_type': 1, 'accelerator_count': 1805}, 'min_replica_count': 1803, 'max_replica_count': 1805, 'autoscaling_metric_specs': [{'metric_name': 'metric_name_value', 'target': 647}]}, 'post_processing_cloud_function': 'post_processing_cloud_function_value', 'attach_application_metadata': True}, 'general_object_detection_config': {}, 'big_query_config': {'table': 'table_value', 'cloud_function_mapping': {}, 'create_default_table_if_not_exists': True}, 'personal_protective_equipment_detection_config': {'enable_face_coverage_detection': True, 'enable_head_coverage_detection': True, 'enable_hands_coverage_detection': True}}, 'processor': 'processor_value', 'parents': [{'parent_node': 'parent_node_value', 'parent_output_channel': 'parent_output_channel_value', 'connected_input_channel': 'connected_input_channel_value'}]}], 'event_delivery_config': {'channel': 'channel_value', 'minimal_delivery_interval': {}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.UpdateDraftRequest.meta.fields["draft"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["draft"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["draft"][field])): + del request_init["draft"][field][i][subfield] + else: + del request_init["draft"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_draft(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_draft] = mock_rpc + + request = {} + client.update_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_draft_rest_required_fields(request_type=platform.UpdateDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_draft._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_draft(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", )) & set(("draft", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateDraftRequest.pb(platform.UpdateDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_draft_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'draft': {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_draft(request) + + +def test_update_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'draft': {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{draft.name=projects/*/locations/*/applications/*/drafts/*}" % client.transport._host, args[1]) + + +def test_update_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_draft( + platform.UpdateDraftRequest(), + draft=platform.Draft(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteDraftRequest, + dict, +]) +def test_delete_draft_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_draft(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_draft_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_draft in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_draft] = mock_rpc + + request = {} + client.delete_draft(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_draft(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_draft_rest_required_fields(request_type=platform.DeleteDraftRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_draft._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_draft._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_draft(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_draft_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_draft._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_draft_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_draft") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_draft") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteDraftRequest.pb(platform.DeleteDraftRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteDraftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_draft(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_draft_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteDraftRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_draft(request) + + +def test_delete_draft_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/applications/sample3/drafts/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_draft(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/applications/*/drafts/*}" % client.transport._host, args[1]) + + +def test_delete_draft_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_draft( + platform.DeleteDraftRequest(), + name='name_value', + ) + + +def test_delete_draft_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.ListProcessorsRequest, + dict, +]) +def test_list_processors_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListProcessorsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_processors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProcessorsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_processors_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_processors] = mock_rpc + + request = {} + client.list_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_processors_rest_required_fields(request_type=platform.ListProcessorsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_processors._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListProcessorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_processors(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_processors_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_processors._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_processors_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_processors") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_processors") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListProcessorsRequest.pb(platform.ListProcessorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListProcessorsResponse.to_json(platform.ListProcessorsResponse()) + + request = platform.ListProcessorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListProcessorsResponse() + + client.list_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_processors_rest_bad_request(transport: str = 'rest', request_type=platform.ListProcessorsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_processors(request) + + +def test_list_processors_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListProcessorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_processors(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_list_processors_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_processors( + platform.ListProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_processors_rest_pager(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + platform.Processor(), + ], + next_page_token='abc', + ), + platform.ListProcessorsResponse( + processors=[], + next_page_token='def', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + ], + next_page_token='ghi', + ), + platform.ListProcessorsResponse( + processors=[ + platform.Processor(), + platform.Processor(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(platform.ListProcessorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_processors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, platform.Processor) + for i in results) + + pages = list(client.list_processors(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + platform.ListPrebuiltProcessorsRequest, + dict, +]) +def test_list_prebuilt_processors_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListPrebuiltProcessorsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListPrebuiltProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_prebuilt_processors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.ListPrebuiltProcessorsResponse) + +def test_list_prebuilt_processors_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_prebuilt_processors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_prebuilt_processors] = mock_rpc + + request = {} + client.list_prebuilt_processors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_prebuilt_processors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_prebuilt_processors_rest_required_fields(request_type=platform.ListPrebuiltProcessorsRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_prebuilt_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_prebuilt_processors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.ListPrebuiltProcessorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.ListPrebuiltProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_prebuilt_processors(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_prebuilt_processors_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_prebuilt_processors._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_prebuilt_processors_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_list_prebuilt_processors") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_list_prebuilt_processors") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.ListPrebuiltProcessorsRequest.pb(platform.ListPrebuiltProcessorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.ListPrebuiltProcessorsResponse.to_json(platform.ListPrebuiltProcessorsResponse()) + + request = platform.ListPrebuiltProcessorsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.ListPrebuiltProcessorsResponse() + + client.list_prebuilt_processors(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_prebuilt_processors_rest_bad_request(transport: str = 'rest', request_type=platform.ListPrebuiltProcessorsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_prebuilt_processors(request) + + +def test_list_prebuilt_processors_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.ListPrebuiltProcessorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.ListPrebuiltProcessorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_prebuilt_processors(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/processors:prebuilt" % client.transport._host, args[1]) + + +def test_list_prebuilt_processors_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_prebuilt_processors( + platform.ListPrebuiltProcessorsRequest(), + parent='parent_value', + ) + + +def test_list_prebuilt_processors_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.GetProcessorRequest, + dict, +]) +def test_get_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Processor( + name='name_value', + display_name='display_name_value', + description='description_value', + processor_type=platform.Processor.ProcessorType.PRETRAINED, + model_type=platform.ModelType.IMAGE_CLASSIFICATION, + state=platform.Processor.ProcessorState.CREATING, + configuration_typeurl='configuration_typeurl_value', + supported_annotation_types=[annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE], + supports_post_processing=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_processor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, platform.Processor) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.processor_type == platform.Processor.ProcessorType.PRETRAINED + assert response.model_type == platform.ModelType.IMAGE_CLASSIFICATION + assert response.state == platform.Processor.ProcessorState.CREATING + assert response.configuration_typeurl == 'configuration_typeurl_value' + assert response.supported_annotation_types == [annotations.StreamAnnotationType.STREAM_ANNOTATION_TYPE_ACTIVE_ZONE] + assert response.supports_post_processing is True + +def test_get_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_processor] = mock_rpc + + request = {} + client.get_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_processor_rest_required_fields(request_type=platform.GetProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = platform.Processor() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = platform.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_get_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_get_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.GetProcessorRequest.pb(platform.GetProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = platform.Processor.to_json(platform.Processor()) + + request = platform.GetProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = platform.Processor() + + client.get_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_processor_rest_bad_request(transport: str = 'rest', request_type=platform.GetProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_processor(request) + + +def test_get_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = platform.Processor() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = platform.Processor.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_get_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_processor( + platform.GetProcessorRequest(), + name='name_value', + ) + + +def test_get_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.CreateProcessorRequest, + dict, +]) +def test_create_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["processor"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'processor_type': 1, 'model_type': 1, 'custom_processor_source_info': {'vertex_model': 'vertex_model_value', 'source_type': 1, 'additional_info': {}, 'model_schema': {'instances_schema': {'uris': ['uris_value1', 'uris_value2']}, 'parameters_schema': {}, 'predictions_schema': {}}}, 'state': 1, 'processor_io_spec': {'graph_input_channel_specs': [{'name': 'name_value', 'data_type': 1, 'accepted_data_type_uris': ['accepted_data_type_uris_value1', 'accepted_data_type_uris_value2'], 'required': True, 'max_connection_allowed': 2332}], 'graph_output_channel_specs': [{'name': 'name_value', 'data_type': 1, 'data_type_uri': 'data_type_uri_value'}], 'instance_resource_input_binding_specs': [{'config_type_uri': 'config_type_uri_value', 'resource_type_uri': 'resource_type_uri_value', 'name': 'name_value'}], 'instance_resource_output_binding_specs': [{'name': 'name_value', 'resource_type_uri': 'resource_type_uri_value', 'explicit': True}]}, 'configuration_typeurl': 'configuration_typeurl_value', 'supported_annotation_types': [1], 'supports_post_processing': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.CreateProcessorRequest.meta.fields["processor"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["processor"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["processor"][field])): + del request_init["processor"][field][i][subfield] + else: + del request_init["processor"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_processor] = mock_rpc + + request = {} + client.create_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_processor_rest_required_fields(request_type=platform.CreateProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["processor_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "processorId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "processorId" in jsonified_request + assert jsonified_request["processorId"] == request_init["processor_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["processorId"] = 'processor_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_processor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("processor_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "processorId" in jsonified_request + assert jsonified_request["processorId"] == 'processor_id_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_processor(request) + + expected_params = [ + ( + "processorId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(("processorId", "requestId", )) & set(("parent", "processorId", "processor", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_create_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_create_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.CreateProcessorRequest.pb(platform.CreateProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.CreateProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_processor_rest_bad_request(transport: str = 'rest', request_type=platform.CreateProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_processor(request) + + +def test_create_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/processors" % client.transport._host, args[1]) + + +def test_create_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_processor( + platform.CreateProcessorRequest(), + parent='parent_value', + processor=platform.Processor(name='name_value'), + processor_id='processor_id_value', + ) + + +def test_create_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.UpdateProcessorRequest, + dict, +]) +def test_update_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'processor': {'name': 'projects/sample1/locations/sample2/processors/sample3'}} + request_init["processor"] = {'name': 'projects/sample1/locations/sample2/processors/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'display_name': 'display_name_value', 'description': 'description_value', 'processor_type': 1, 'model_type': 1, 'custom_processor_source_info': {'vertex_model': 'vertex_model_value', 'source_type': 1, 'additional_info': {}, 'model_schema': {'instances_schema': {'uris': ['uris_value1', 'uris_value2']}, 'parameters_schema': {}, 'predictions_schema': {}}}, 'state': 1, 'processor_io_spec': {'graph_input_channel_specs': [{'name': 'name_value', 'data_type': 1, 'accepted_data_type_uris': ['accepted_data_type_uris_value1', 'accepted_data_type_uris_value2'], 'required': True, 'max_connection_allowed': 2332}], 'graph_output_channel_specs': [{'name': 'name_value', 'data_type': 1, 'data_type_uri': 'data_type_uri_value'}], 'instance_resource_input_binding_specs': [{'config_type_uri': 'config_type_uri_value', 'resource_type_uri': 'resource_type_uri_value', 'name': 'name_value'}], 'instance_resource_output_binding_specs': [{'name': 'name_value', 'resource_type_uri': 'resource_type_uri_value', 'explicit': True}]}, 'configuration_typeurl': 'configuration_typeurl_value', 'supported_annotation_types': [1], 'supports_post_processing': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = platform.UpdateProcessorRequest.meta.fields["processor"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["processor"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["processor"][field])): + del request_init["processor"][field][i][subfield] + else: + del request_init["processor"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_processor] = mock_rpc + + request = {} + client.update_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_processor_rest_required_fields(request_type=platform.UpdateProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_processor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("processor", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_update_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_update_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.UpdateProcessorRequest.pb(platform.UpdateProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.UpdateProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_processor_rest_bad_request(transport: str = 'rest', request_type=platform.UpdateProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'processor': {'name': 'projects/sample1/locations/sample2/processors/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_processor(request) + + +def test_update_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'processor': {'name': 'projects/sample1/locations/sample2/processors/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{processor.name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_update_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_processor( + platform.UpdateProcessorRequest(), + processor=platform.Processor(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + platform.DeleteProcessorRequest, + dict, +]) +def test_delete_processor_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_processor(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_processor_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_processor in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_processor] = mock_rpc + + request = {} + client.delete_processor(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_processor(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_processor_rest_required_fields(request_type=platform.DeleteProcessorRequest): + transport_class = transports.AppPlatformRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_processor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_processor(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_processor_rest_unset_required_fields(): + transport = transports.AppPlatformRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_processor._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_processor_rest_interceptors(null_interceptor): + transport = transports.AppPlatformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AppPlatformRestInterceptor(), + ) + client = AppPlatformClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AppPlatformRestInterceptor, "post_delete_processor") as post, \ + mock.patch.object(transports.AppPlatformRestInterceptor, "pre_delete_processor") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = platform.DeleteProcessorRequest.pb(platform.DeleteProcessorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = platform.DeleteProcessorRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_processor(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_processor_rest_bad_request(transport: str = 'rest', request_type=platform.DeleteProcessorRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_processor(request) + + +def test_delete_processor_rest_flattened(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/processors/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_processor(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/processors/*}" % client.transport._host, args[1]) + + +def test_delete_processor_rest_flattened_error(transport: str = 'rest'): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_processor( + platform.DeleteProcessorRequest(), + name='name_value', + ) + + +def test_delete_processor_rest_error(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AppPlatformClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AppPlatformClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AppPlatformGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AppPlatformGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformGrpcAsyncIOTransport, + transports.AppPlatformRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = AppPlatformClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AppPlatformGrpcTransport, + ) + +def test_app_platform_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AppPlatformTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_app_platform_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1alpha1.services.app_platform.transports.AppPlatformTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AppPlatformTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_applications', + 'get_application', + 'create_application', + 'update_application', + 'delete_application', + 'deploy_application', + 'undeploy_application', + 'add_application_stream_input', + 'remove_application_stream_input', + 'update_application_stream_input', + 'list_instances', + 'get_instance', + 'create_application_instances', + 'delete_application_instances', + 'update_application_instances', + 'list_drafts', + 'get_draft', + 'create_draft', + 'update_draft', + 'delete_draft', + 'list_processors', + 'list_prebuilt_processors', + 'get_processor', + 'create_processor', + 'update_processor', + 'delete_processor', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_app_platform_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1alpha1.services.app_platform.transports.AppPlatformTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AppPlatformTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_app_platform_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1alpha1.services.app_platform.transports.AppPlatformTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AppPlatformTransport() + adc.assert_called_once() + + +def test_app_platform_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) + AppPlatformClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformGrpcAsyncIOTransport, + ], +) +def test_app_platform_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AppPlatformGrpcTransport, + transports.AppPlatformGrpcAsyncIOTransport, + transports.AppPlatformRestTransport, + ], +) +def test_app_platform_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AppPlatformGrpcTransport, grpc_helpers), + (transports.AppPlatformGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_app_platform_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( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AppPlatformGrpcTransport, transports.AppPlatformGrpcAsyncIOTransport]) +def test_app_platform_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_app_platform_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.AppPlatformRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_app_platform_rest_lro_client(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_app_platform_host_no_port(transport_name): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_app_platform_host_with_port(transport_name): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_app_platform_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AppPlatformClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AppPlatformClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_applications._session + session2 = client2.transport.list_applications._session + assert session1 != session2 + session1 = client1.transport.get_application._session + session2 = client2.transport.get_application._session + assert session1 != session2 + session1 = client1.transport.create_application._session + session2 = client2.transport.create_application._session + assert session1 != session2 + session1 = client1.transport.update_application._session + session2 = client2.transport.update_application._session + assert session1 != session2 + session1 = client1.transport.delete_application._session + session2 = client2.transport.delete_application._session + assert session1 != session2 + session1 = client1.transport.deploy_application._session + session2 = client2.transport.deploy_application._session + assert session1 != session2 + session1 = client1.transport.undeploy_application._session + session2 = client2.transport.undeploy_application._session + assert session1 != session2 + session1 = client1.transport.add_application_stream_input._session + session2 = client2.transport.add_application_stream_input._session + assert session1 != session2 + session1 = client1.transport.remove_application_stream_input._session + session2 = client2.transport.remove_application_stream_input._session + assert session1 != session2 + session1 = client1.transport.update_application_stream_input._session + session2 = client2.transport.update_application_stream_input._session + assert session1 != session2 + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_application_instances._session + session2 = client2.transport.create_application_instances._session + assert session1 != session2 + session1 = client1.transport.delete_application_instances._session + session2 = client2.transport.delete_application_instances._session + assert session1 != session2 + session1 = client1.transport.update_application_instances._session + session2 = client2.transport.update_application_instances._session + assert session1 != session2 + session1 = client1.transport.list_drafts._session + session2 = client2.transport.list_drafts._session + assert session1 != session2 + session1 = client1.transport.get_draft._session + session2 = client2.transport.get_draft._session + assert session1 != session2 + session1 = client1.transport.create_draft._session + session2 = client2.transport.create_draft._session + assert session1 != session2 + session1 = client1.transport.update_draft._session + session2 = client2.transport.update_draft._session + assert session1 != session2 + session1 = client1.transport.delete_draft._session + session2 = client2.transport.delete_draft._session + assert session1 != session2 + session1 = client1.transport.list_processors._session + session2 = client2.transport.list_processors._session + assert session1 != session2 + session1 = client1.transport.list_prebuilt_processors._session + session2 = client2.transport.list_prebuilt_processors._session + assert session1 != session2 + session1 = client1.transport.get_processor._session + session2 = client2.transport.get_processor._session + assert session1 != session2 + session1 = client1.transport.create_processor._session + session2 = client2.transport.create_processor._session + assert session1 != session2 + session1 = client1.transport.update_processor._session + session2 = client2.transport.update_processor._session + assert session1 != session2 + session1 = client1.transport.delete_processor._session + session2 = client2.transport.delete_processor._session + assert session1 != session2 +def test_app_platform_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AppPlatformGrpcTransport( + 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_app_platform_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AppPlatformGrpcAsyncIOTransport( + 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.AppPlatformGrpcTransport, transports.AppPlatformGrpcAsyncIOTransport]) +def test_app_platform_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.AppPlatformGrpcTransport, transports.AppPlatformGrpcAsyncIOTransport]) +def test_app_platform_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_app_platform_grpc_lro_client(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_app_platform_grpc_lro_async_client(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_application_path(): + project = "squid" + location = "clam" + application = "whelk" + expected = "projects/{project}/locations/{location}/applications/{application}".format(project=project, location=location, application=application, ) + actual = AppPlatformClient.application_path(project, location, application) + assert expected == actual + + +def test_parse_application_path(): + expected = { + "project": "octopus", + "location": "oyster", + "application": "nudibranch", + } + path = AppPlatformClient.application_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_application_path(path) + assert expected == actual + +def test_draft_path(): + project = "cuttlefish" + location = "mussel" + application = "winkle" + draft = "nautilus" + expected = "projects/{project}/locations/{location}/applications/{application}/drafts/{draft}".format(project=project, location=location, application=application, draft=draft, ) + actual = AppPlatformClient.draft_path(project, location, application, draft) + assert expected == actual + + +def test_parse_draft_path(): + expected = { + "project": "scallop", + "location": "abalone", + "application": "squid", + "draft": "clam", + } + path = AppPlatformClient.draft_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_draft_path(path) + assert expected == actual + +def test_instance_path(): + project = "whelk" + location = "octopus" + application = "oyster" + instance = "nudibranch" + expected = "projects/{project}/locations/{location}/applications/{application}/instances/{instance}".format(project=project, location=location, application=application, instance=instance, ) + actual = AppPlatformClient.instance_path(project, location, application, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "application": "winkle", + "instance": "nautilus", + } + path = AppPlatformClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_instance_path(path) + assert expected == actual + +def test_processor_path(): + project = "scallop" + location = "abalone" + processor = "squid" + expected = "projects/{project}/locations/{location}/processors/{processor}".format(project=project, location=location, processor=processor, ) + actual = AppPlatformClient.processor_path(project, location, processor) + assert expected == actual + + +def test_parse_processor_path(): + expected = { + "project": "clam", + "location": "whelk", + "processor": "octopus", + } + path = AppPlatformClient.processor_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_processor_path(path) + assert expected == actual + +def test_stream_path(): + project = "oyster" + location = "nudibranch" + cluster = "cuttlefish" + stream = "mussel" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + actual = AppPlatformClient.stream_path(project, location, cluster, stream) + assert expected == actual + + +def test_parse_stream_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "cluster": "scallop", + "stream": "abalone", + } + path = AppPlatformClient.stream_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_stream_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AppPlatformClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AppPlatformClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AppPlatformClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AppPlatformClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AppPlatformClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AppPlatformClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AppPlatformClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AppPlatformClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AppPlatformClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AppPlatformClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AppPlatformClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.AppPlatformTransport, '_prep_wrapped_messages') as prep: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AppPlatformTransport, '_prep_wrapped_messages') as prep: + transport_class = AppPlatformClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = AppPlatformAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = AppPlatformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (AppPlatformClient, transports.AppPlatformGrpcTransport), + (AppPlatformAsyncClient, transports.AppPlatformGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_live_video_analytics.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_live_video_analytics.py new file mode 100644 index 000000000000..98af343614d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_live_video_analytics.py @@ -0,0 +1,6778 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1alpha1.services.live_video_analytics import LiveVideoAnalyticsAsyncClient +from google.cloud.visionai_v1alpha1.services.live_video_analytics import LiveVideoAnalyticsClient +from google.cloud.visionai_v1alpha1.services.live_video_analytics import pagers +from google.cloud.visionai_v1alpha1.services.live_video_analytics import transports +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import lva +from google.cloud.visionai_v1alpha1.types import lva_resources +from google.cloud.visionai_v1alpha1.types import lva_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 LiveVideoAnalyticsClient._get_default_mtls_endpoint(None) is None + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LiveVideoAnalyticsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LiveVideoAnalyticsClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LiveVideoAnalyticsClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert LiveVideoAnalyticsClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert LiveVideoAnalyticsClient._get_client_cert_source(None, False) is None + assert LiveVideoAnalyticsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LiveVideoAnalyticsClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert LiveVideoAnalyticsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LiveVideoAnalyticsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + default_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LiveVideoAnalyticsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LiveVideoAnalyticsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, default_universe, "always") == LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + assert LiveVideoAnalyticsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LiveVideoAnalyticsClient.DEFAULT_MTLS_ENDPOINT + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LiveVideoAnalyticsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LiveVideoAnalyticsClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert LiveVideoAnalyticsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LiveVideoAnalyticsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LiveVideoAnalyticsClient._get_universe_domain(None, None) == LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LiveVideoAnalyticsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LiveVideoAnalyticsClient, "grpc"), + (LiveVideoAnalyticsAsyncClient, "grpc_asyncio"), + (LiveVideoAnalyticsClient, "rest"), +]) +def test_live_video_analytics_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +def test_live_video_analytics_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (LiveVideoAnalyticsClient, "grpc"), + (LiveVideoAnalyticsAsyncClient, "grpc_asyncio"), + (LiveVideoAnalyticsClient, "rest"), +]) +def test_live_video_analytics_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_live_video_analytics_client_get_transport_class(): + transport = LiveVideoAnalyticsClient.get_transport_class() + available_transports = [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsRestTransport, + ] + assert transport in available_transports + + transport = LiveVideoAnalyticsClient.get_transport_class("grpc") + assert transport == transports.LiveVideoAnalyticsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +def test_live_video_analytics_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(LiveVideoAnalyticsClient, '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(LiveVideoAnalyticsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", "true"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", "false"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest", "true"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest", "false"), +]) +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_live_video_analytics_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + LiveVideoAnalyticsClient, LiveVideoAnalyticsAsyncClient +]) +@mock.patch.object(LiveVideoAnalyticsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LiveVideoAnalyticsAsyncClient)) +def test_live_video_analytics_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + LiveVideoAnalyticsClient, LiveVideoAnalyticsAsyncClient +]) +@mock.patch.object(LiveVideoAnalyticsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsClient)) +@mock.patch.object(LiveVideoAnalyticsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LiveVideoAnalyticsAsyncClient)) +def test_live_video_analytics_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LiveVideoAnalyticsClient._DEFAULT_UNIVERSE + default_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LiveVideoAnalyticsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc"), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio"), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest"), +]) +def test_live_video_analytics_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", grpc_helpers), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsRestTransport, "rest", None), +]) +def test_live_video_analytics_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_live_video_analytics_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1alpha1.services.live_video_analytics.transports.LiveVideoAnalyticsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LiveVideoAnalyticsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport, "grpc", grpc_helpers), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_live_video_analytics_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListAnalysesRequest, + dict, +]) +def test_list_analyses(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.ListAnalysesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnalysesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_analyses_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 = LiveVideoAnalyticsClient( + 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_analyses), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_analyses() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListAnalysesRequest() + + +def test_list_analyses_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.ListAnalysesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_analyses(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListAnalysesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_analyses_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_analyses in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_analyses] = mock_rpc + request = {} + client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_analyses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_analyses_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_analyses() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.ListAnalysesRequest() + +@pytest.mark.asyncio +async def test_list_analyses_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_analyses in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_analyses] = mock_object + + request = {} + await client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_analyses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_analyses_async(transport: str = 'grpc_asyncio', request_type=lva_service.ListAnalysesRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.ListAnalysesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnalysesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_analyses_async_from_dict(): + await test_list_analyses_async(request_type=dict) + + +def test_list_analyses_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListAnalysesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + call.return_value = lva_service.ListAnalysesResponse() + client.list_analyses(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_analyses_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.ListAnalysesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse()) + await client.list_analyses(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_analyses_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListAnalysesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_analyses( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_analyses_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analyses( + lva_service.ListAnalysesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_analyses_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_service.ListAnalysesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_service.ListAnalysesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_analyses( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_analyses_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analyses( + lva_service.ListAnalysesRequest(), + parent='parent_value', + ) + + +def test_list_analyses_pager(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_analyses(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Analysis) + for i in results) +def test_list_analyses_pages(transport_name: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + pages = list(client.list_analyses(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_analyses_async_pager(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_analyses(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, lva_resources.Analysis) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_analyses_async_pages(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_analyses), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_analyses(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + lva_service.GetAnalysisRequest, + dict, +]) +def test_get_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Analysis( + name='name_value', + ) + response = client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.GetAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Analysis) + assert response.name == 'name_value' + + +def test_get_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetAnalysisRequest() + + +def test_get_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.GetAnalysisRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetAnalysisRequest( + name='name_value', + ) + +def test_get_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_analysis] = mock_rpc + request = {} + client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis( + name='name_value', + )) + response = await client.get_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.GetAnalysisRequest() + +@pytest.mark.asyncio +async def test_get_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_analysis] = mock_object + + request = {} + await client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.GetAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis( + name='name_value', + )) + response = await client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.GetAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Analysis) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_analysis_async_from_dict(): + await test_get_analysis_async(request_type=dict) + + +def test_get_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + call.return_value = lva_resources.Analysis() + client.get_analysis(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_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.GetAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis()) + await client.get_analysis(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_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Analysis() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.GetAnalysisRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lva_resources.Analysis() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lva_resources.Analysis()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.GetAnalysisRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateAnalysisRequest, + dict, +]) +def test_create_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.CreateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateAnalysisRequest() + + +def test_create_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.CreateAnalysisRequest( + parent='parent_value', + analysis_id='analysis_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateAnalysisRequest( + parent='parent_value', + analysis_id='analysis_id_value', + request_id='request_id_value', + ) + +def test_create_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_analysis] = mock_rpc + request = {} + client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.CreateAnalysisRequest() + +@pytest.mark.asyncio +async def test_create_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_analysis] = mock_object + + request = {} + await client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.CreateAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.CreateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_analysis_async_from_dict(): + await test_create_analysis_async(request_type=dict) + + +def test_create_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateAnalysisRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_analysis(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_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.CreateAnalysisRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_analysis(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_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_analysis( + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].analysis_id + mock_val = 'analysis_id_value' + assert arg == mock_val + + +def test_create_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.CreateAnalysisRequest(), + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + +@pytest.mark.asyncio +async def test_create_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_analysis( + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].analysis_id + mock_val = 'analysis_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.CreateAnalysisRequest(), + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateAnalysisRequest, + dict, +]) +def test_update_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateAnalysisRequest() + + +def test_update_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.UpdateAnalysisRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateAnalysisRequest( + request_id='request_id_value', + ) + +def test_update_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_analysis] = mock_rpc + request = {} + client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.UpdateAnalysisRequest() + +@pytest.mark.asyncio +async def test_update_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_analysis] = mock_object + + request = {} + await client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.UpdateAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.UpdateAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_analysis_async_from_dict(): + await test_update_analysis_async(request_type=dict) + + +def test_update_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateAnalysisRequest() + + request.analysis.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_analysis(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', + 'analysis.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.UpdateAnalysisRequest() + + request.analysis.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_analysis(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', + 'analysis.name=name_value', + ) in kw['metadata'] + + +def test_update_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_analysis( + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.UpdateAnalysisRequest(), + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_analysis( + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].analysis + mock_val = lva_resources.Analysis(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.UpdateAnalysisRequest(), + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteAnalysisRequest, + dict, +]) +def test_delete_analysis(request_type, transport: str = 'grpc'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_analysis_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 = LiveVideoAnalyticsClient( + 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_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteAnalysisRequest() + + +def test_delete_analysis_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = lva_service.DeleteAnalysisRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_analysis(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteAnalysisRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_analysis_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_analysis] = mock_rpc + request = {} + client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_analysis_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lva_service.DeleteAnalysisRequest() + +@pytest.mark.asyncio +async def test_delete_analysis_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_analysis in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_analysis] = mock_object + + request = {} + await client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_analysis_async(transport: str = 'grpc_asyncio', request_type=lva_service.DeleteAnalysisRequest): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lva_service.DeleteAnalysisRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_analysis_async_from_dict(): + await test_delete_analysis_async(request_type=dict) + + +def test_delete_analysis_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_analysis(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_analysis_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = lva_service.DeleteAnalysisRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_analysis(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_analysis_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_analysis_flattened_error(): + client = LiveVideoAnalyticsClient( + 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_analysis( + lva_service.DeleteAnalysisRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_analysis_flattened_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_analysis( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_analysis_flattened_error_async(): + client = LiveVideoAnalyticsAsyncClient( + 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_analysis( + lva_service.DeleteAnalysisRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.ListAnalysesRequest, + dict, +]) +def test_list_analyses_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListAnalysesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListAnalysesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_analyses(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnalysesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_analyses_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_analyses in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_analyses] = mock_rpc + + request = {} + client.list_analyses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_analyses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_analyses_rest_required_fields(request_type=lva_service.ListAnalysesRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_analyses._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_analyses._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_service.ListAnalysesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_service.ListAnalysesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_analyses(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_analyses_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_analyses._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_analyses_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_list_analyses") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_list_analyses") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.ListAnalysesRequest.pb(lva_service.ListAnalysesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_service.ListAnalysesResponse.to_json(lva_service.ListAnalysesResponse()) + + request = lva_service.ListAnalysesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_service.ListAnalysesResponse() + + client.list_analyses(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_analyses_rest_bad_request(transport: str = 'rest', request_type=lva_service.ListAnalysesRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_analyses(request) + + +def test_list_analyses_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_service.ListAnalysesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_service.ListAnalysesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_analyses(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/analyses" % client.transport._host, args[1]) + + +def test_list_analyses_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_analyses( + lva_service.ListAnalysesRequest(), + parent='parent_value', + ) + + +def test_list_analyses_rest_pager(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + next_page_token='abc', + ), + lva_service.ListAnalysesResponse( + analyses=[], + next_page_token='def', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + ], + next_page_token='ghi', + ), + lva_service.ListAnalysesResponse( + analyses=[ + lva_resources.Analysis(), + lva_resources.Analysis(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lva_service.ListAnalysesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_analyses(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lva_resources.Analysis) + for i in results) + + pages = list(client.list_analyses(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + lva_service.GetAnalysisRequest, + dict, +]) +def test_get_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Analysis( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Analysis.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_analysis(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lva_resources.Analysis) + assert response.name == 'name_value' + +def test_get_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_analysis] = mock_rpc + + request = {} + client.get_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_analysis_rest_required_fields(request_type=lva_service.GetAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lva_resources.Analysis() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = lva_resources.Analysis.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_analysis(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_get_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_get_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.GetAnalysisRequest.pb(lva_service.GetAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = lva_resources.Analysis.to_json(lva_resources.Analysis()) + + request = lva_service.GetAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lva_resources.Analysis() + + client.get_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.GetAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_analysis(request) + + +def test_get_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = lva_resources.Analysis() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = lva_resources.Analysis.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/analyses/*}" % client.transport._host, args[1]) + + +def test_get_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_analysis( + lva_service.GetAnalysisRequest(), + name='name_value', + ) + + +def test_get_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.CreateAnalysisRequest, + dict, +]) +def test_create_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["analysis"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'analysis_definition': {'analyzers': [{'analyzer': 'analyzer_value', 'operator': 'operator_value', 'inputs': [{'input': 'input_value'}], 'attrs': {}, 'debug_options': {'environment_variables': {}}}]}, 'input_streams_mapping': {}, 'output_streams_mapping': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.CreateAnalysisRequest.meta.fields["analysis"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["analysis"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["analysis"][field])): + del request_init["analysis"][field][i][subfield] + else: + del request_init["analysis"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_analysis(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_analysis] = mock_rpc + + request = {} + client.create_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_analysis_rest_required_fields(request_type=lva_service.CreateAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["analysis_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "analysisId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "analysisId" in jsonified_request + assert jsonified_request["analysisId"] == request_init["analysis_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["analysisId"] = 'analysis_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_analysis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("analysis_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "analysisId" in jsonified_request + assert jsonified_request["analysisId"] == 'analysis_id_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_analysis(request) + + expected_params = [ + ( + "analysisId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(("analysisId", "requestId", )) & set(("parent", "analysisId", "analysis", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_create_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_create_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.CreateAnalysisRequest.pb(lva_service.CreateAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.CreateAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.CreateAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_analysis(request) + + +def test_create_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/analyses" % client.transport._host, args[1]) + + +def test_create_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_analysis( + lva_service.CreateAnalysisRequest(), + parent='parent_value', + analysis=lva_resources.Analysis(name='name_value'), + analysis_id='analysis_id_value', + ) + + +def test_create_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.UpdateAnalysisRequest, + dict, +]) +def test_update_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'analysis': {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'}} + request_init["analysis"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'analysis_definition': {'analyzers': [{'analyzer': 'analyzer_value', 'operator': 'operator_value', 'inputs': [{'input': 'input_value'}], 'attrs': {}, 'debug_options': {'environment_variables': {}}}]}, 'input_streams_mapping': {}, 'output_streams_mapping': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = lva_service.UpdateAnalysisRequest.meta.fields["analysis"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["analysis"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["analysis"][field])): + del request_init["analysis"][field][i][subfield] + else: + del request_init["analysis"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_analysis(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_analysis] = mock_rpc + + request = {} + client.update_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_analysis_rest_required_fields(request_type=lva_service.UpdateAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_analysis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_analysis(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "analysis", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_update_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_update_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.UpdateAnalysisRequest.pb(lva_service.UpdateAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.UpdateAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.UpdateAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'analysis': {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_analysis(request) + + +def test_update_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'analysis': {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{analysis.name=projects/*/locations/*/clusters/*/analyses/*}" % client.transport._host, args[1]) + + +def test_update_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_analysis( + lva_service.UpdateAnalysisRequest(), + analysis=lva_resources.Analysis(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + lva_service.DeleteAnalysisRequest, + dict, +]) +def test_delete_analysis_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_analysis(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_analysis_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_analysis in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_analysis] = mock_rpc + + request = {} + client.delete_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_analysis(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_analysis_rest_required_fields(request_type=lva_service.DeleteAnalysisRequest): + transport_class = transports.LiveVideoAnalyticsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_analysis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_analysis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_analysis(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_analysis_rest_unset_required_fields(): + transport = transports.LiveVideoAnalyticsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_analysis._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_analysis_rest_interceptors(null_interceptor): + transport = transports.LiveVideoAnalyticsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LiveVideoAnalyticsRestInterceptor(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "post_delete_analysis") as post, \ + mock.patch.object(transports.LiveVideoAnalyticsRestInterceptor, "pre_delete_analysis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lva_service.DeleteAnalysisRequest.pb(lva_service.DeleteAnalysisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = lva_service.DeleteAnalysisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_analysis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_analysis_rest_bad_request(transport: str = 'rest', request_type=lva_service.DeleteAnalysisRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_analysis(request) + + +def test_delete_analysis_rest_flattened(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/analyses/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_analysis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/analyses/*}" % client.transport._host, args[1]) + + +def test_delete_analysis_rest_flattened_error(transport: str = 'rest'): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_analysis( + lva_service.DeleteAnalysisRequest(), + name='name_value', + ) + + +def test_delete_analysis_rest_error(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LiveVideoAnalyticsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LiveVideoAnalyticsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LiveVideoAnalyticsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LiveVideoAnalyticsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsGrpcAsyncIOTransport, + transports.LiveVideoAnalyticsRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = LiveVideoAnalyticsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LiveVideoAnalyticsGrpcTransport, + ) + +def test_live_video_analytics_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LiveVideoAnalyticsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_live_video_analytics_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1alpha1.services.live_video_analytics.transports.LiveVideoAnalyticsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LiveVideoAnalyticsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_analyses', + 'get_analysis', + 'create_analysis', + 'update_analysis', + 'delete_analysis', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_live_video_analytics_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1alpha1.services.live_video_analytics.transports.LiveVideoAnalyticsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LiveVideoAnalyticsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_live_video_analytics_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1alpha1.services.live_video_analytics.transports.LiveVideoAnalyticsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LiveVideoAnalyticsTransport() + adc.assert_called_once() + + +def test_live_video_analytics_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) + LiveVideoAnalyticsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsGrpcAsyncIOTransport, + ], +) +def test_live_video_analytics_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LiveVideoAnalyticsGrpcTransport, + transports.LiveVideoAnalyticsGrpcAsyncIOTransport, + transports.LiveVideoAnalyticsRestTransport, + ], +) +def test_live_video_analytics_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LiveVideoAnalyticsGrpcTransport, grpc_helpers), + (transports.LiveVideoAnalyticsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_live_video_analytics_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( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LiveVideoAnalyticsGrpcTransport, transports.LiveVideoAnalyticsGrpcAsyncIOTransport]) +def test_live_video_analytics_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_live_video_analytics_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.LiveVideoAnalyticsRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_live_video_analytics_rest_lro_client(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_live_video_analytics_host_no_port(transport_name): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_live_video_analytics_host_with_port(transport_name): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_live_video_analytics_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LiveVideoAnalyticsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LiveVideoAnalyticsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_analyses._session + session2 = client2.transport.list_analyses._session + assert session1 != session2 + session1 = client1.transport.get_analysis._session + session2 = client2.transport.get_analysis._session + assert session1 != session2 + session1 = client1.transport.create_analysis._session + session2 = client2.transport.create_analysis._session + assert session1 != session2 + session1 = client1.transport.update_analysis._session + session2 = client2.transport.update_analysis._session + assert session1 != session2 + session1 = client1.transport.delete_analysis._session + session2 = client2.transport.delete_analysis._session + assert session1 != session2 +def test_live_video_analytics_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LiveVideoAnalyticsGrpcTransport( + 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_live_video_analytics_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LiveVideoAnalyticsGrpcAsyncIOTransport( + 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.LiveVideoAnalyticsGrpcTransport, transports.LiveVideoAnalyticsGrpcAsyncIOTransport]) +def test_live_video_analytics_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.LiveVideoAnalyticsGrpcTransport, transports.LiveVideoAnalyticsGrpcAsyncIOTransport]) +def test_live_video_analytics_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_live_video_analytics_grpc_lro_client(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_live_video_analytics_grpc_lro_async_client(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_analysis_path(): + project = "squid" + location = "clam" + cluster = "whelk" + analysis = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/analyses/{analysis}".format(project=project, location=location, cluster=cluster, analysis=analysis, ) + actual = LiveVideoAnalyticsClient.analysis_path(project, location, cluster, analysis) + assert expected == actual + + +def test_parse_analysis_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "analysis": "mussel", + } + path = LiveVideoAnalyticsClient.analysis_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_analysis_path(path) + assert expected == actual + +def test_cluster_path(): + project = "winkle" + location = "nautilus" + cluster = "scallop" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = LiveVideoAnalyticsClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "abalone", + "location": "squid", + "cluster": "clam", + } + path = LiveVideoAnalyticsClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_cluster_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LiveVideoAnalyticsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = LiveVideoAnalyticsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = LiveVideoAnalyticsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = LiveVideoAnalyticsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LiveVideoAnalyticsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = LiveVideoAnalyticsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = LiveVideoAnalyticsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = LiveVideoAnalyticsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LiveVideoAnalyticsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = LiveVideoAnalyticsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LiveVideoAnalyticsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.LiveVideoAnalyticsTransport, '_prep_wrapped_messages') as prep: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LiveVideoAnalyticsTransport, '_prep_wrapped_messages') as prep: + transport_class = LiveVideoAnalyticsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = LiveVideoAnalyticsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = LiveVideoAnalyticsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (LiveVideoAnalyticsClient, transports.LiveVideoAnalyticsGrpcTransport), + (LiveVideoAnalyticsAsyncClient, transports.LiveVideoAnalyticsGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_streaming_service.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_streaming_service.py new file mode 100644 index 000000000000..b74445fdd89e --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_streaming_service.py @@ -0,0 +1,4906 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1alpha1.services.streaming_service import StreamingServiceAsyncClient +from google.cloud.visionai_v1alpha1.services.streaming_service import StreamingServiceClient +from google.cloud.visionai_v1alpha1.services.streaming_service import transports +from google.cloud.visionai_v1alpha1.types import streaming_resources +from google.cloud.visionai_v1alpha1.types import streaming_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 StreamingServiceClient._get_default_mtls_endpoint(None) is None + assert StreamingServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert StreamingServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert StreamingServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + StreamingServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert StreamingServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert StreamingServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamingServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert StreamingServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert StreamingServiceClient._get_client_cert_source(None, False) is None + assert StreamingServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert StreamingServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert StreamingServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert StreamingServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert StreamingServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert StreamingServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamingServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert StreamingServiceClient._get_api_endpoint(None, None, default_universe, "always") == StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamingServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == StreamingServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamingServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert StreamingServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamingServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert StreamingServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert StreamingServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert StreamingServiceClient._get_universe_domain(None, None) == StreamingServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + StreamingServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamingServiceClient, "grpc"), + (StreamingServiceAsyncClient, "grpc_asyncio"), + (StreamingServiceClient, "rest"), +]) +def test_streaming_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.StreamingServiceGrpcTransport, "grpc"), + (transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.StreamingServiceRestTransport, "rest"), +]) +def test_streaming_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamingServiceClient, "grpc"), + (StreamingServiceAsyncClient, "grpc_asyncio"), + (StreamingServiceClient, "rest"), +]) +def test_streaming_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_streaming_service_client_get_transport_class(): + transport = StreamingServiceClient.get_transport_class() + available_transports = [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceRestTransport, + ] + assert transport in available_transports + + transport = StreamingServiceClient.get_transport_class("grpc") + assert transport == transports.StreamingServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest"), +]) +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +def test_streaming_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(StreamingServiceClient, '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(StreamingServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", "true"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", "false"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest", "true"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_streaming_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + StreamingServiceClient, StreamingServiceAsyncClient +]) +@mock.patch.object(StreamingServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingServiceAsyncClient)) +def test_streaming_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + StreamingServiceClient, StreamingServiceAsyncClient +]) +@mock.patch.object(StreamingServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceClient)) +@mock.patch.object(StreamingServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamingServiceAsyncClient)) +def test_streaming_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = StreamingServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamingServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc"), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest"), +]) +def test_streaming_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", grpc_helpers), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (StreamingServiceClient, transports.StreamingServiceRestTransport, "rest", None), +]) +def test_streaming_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_streaming_service_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1alpha1.services.streaming_service.transports.StreamingServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = StreamingServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport, "grpc", grpc_helpers), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_streaming_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.SendPacketsRequest, + dict, +]) +def test_send_packets(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([streaming_service.SendPacketsResponse()]) + response = client.send_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, streaming_service.SendPacketsResponse) + + +def test_send_packets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.send_packets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.send_packets] = mock_rpc + request = [{}] + client.send_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_send_packets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.send_packets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.send_packets] = mock_object + + request = [{}] + await client.send_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.send_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_send_packets_async(transport: str = 'grpc_asyncio', request_type=streaming_service.SendPacketsRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[streaming_service.SendPacketsResponse()]) + response = await client.send_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, streaming_service.SendPacketsResponse) + + +@pytest.mark.asyncio +async def test_send_packets_async_from_dict(): + await test_send_packets_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReceivePacketsRequest, + dict, +]) +def test_receive_packets(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([streaming_service.ReceivePacketsResponse()]) + response = client.receive_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, streaming_service.ReceivePacketsResponse) + + +def test_receive_packets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.receive_packets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.receive_packets] = mock_rpc + request = [{}] + client.receive_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.receive_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_receive_packets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.receive_packets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.receive_packets] = mock_object + + request = [{}] + await client.receive_packets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.receive_packets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_receive_packets_async(transport: str = 'grpc_asyncio', request_type=streaming_service.ReceivePacketsRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_packets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[streaming_service.ReceivePacketsResponse()]) + response = await client.receive_packets(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, streaming_service.ReceivePacketsResponse) + + +@pytest.mark.asyncio +async def test_receive_packets_async_from_dict(): + await test_receive_packets_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReceiveEventsRequest, + dict, +]) +def test_receive_events(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([streaming_service.ReceiveEventsResponse()]) + response = client.receive_events(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, streaming_service.ReceiveEventsResponse) + + +def test_receive_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.receive_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.receive_events] = mock_rpc + request = [{}] + client.receive_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.receive_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_receive_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.receive_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.receive_events] = mock_object + + request = [{}] + await client.receive_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.receive_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_receive_events_async(transport: str = 'grpc_asyncio', request_type=streaming_service.ReceiveEventsRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.receive_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[streaming_service.ReceiveEventsResponse()]) + response = await client.receive_events(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, streaming_service.ReceiveEventsResponse) + + +@pytest.mark.asyncio +async def test_receive_events_async_from_dict(): + await test_receive_events_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.AcquireLeaseRequest, + dict, +]) +def test_acquire_lease(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + response = client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streaming_service.AcquireLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +def test_acquire_lease_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 = StreamingServiceClient( + 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.acquire_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acquire_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.AcquireLeaseRequest() + + +def test_acquire_lease_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streaming_service.AcquireLeaseRequest( + series='series_value', + owner='owner_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acquire_lease(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.AcquireLeaseRequest( + series='series_value', + owner='owner_value', + ) + +def test_acquire_lease_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acquire_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acquire_lease] = mock_rpc + request = {} + client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acquire_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_acquire_lease_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.acquire_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.AcquireLeaseRequest() + +@pytest.mark.asyncio +async def test_acquire_lease_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.acquire_lease in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.acquire_lease] = mock_object + + request = {} + await client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.acquire_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_acquire_lease_async(transport: str = 'grpc_asyncio', request_type=streaming_service.AcquireLeaseRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streaming_service.AcquireLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +@pytest.mark.asyncio +async def test_acquire_lease_async_from_dict(): + await test_acquire_lease_async(request_type=dict) + + +def test_acquire_lease_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.AcquireLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + call.return_value = streaming_service.Lease() + client.acquire_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_acquire_lease_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.AcquireLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acquire_lease), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease()) + await client.acquire_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + streaming_service.RenewLeaseRequest, + dict, +]) +def test_renew_lease(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + response = client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streaming_service.RenewLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +def test_renew_lease_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 = StreamingServiceClient( + 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.renew_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.renew_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.RenewLeaseRequest() + + +def test_renew_lease_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streaming_service.RenewLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.renew_lease(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.RenewLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + +def test_renew_lease_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.renew_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.renew_lease] = mock_rpc + request = {} + client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.renew_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_renew_lease_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.renew_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.RenewLeaseRequest() + +@pytest.mark.asyncio +async def test_renew_lease_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.renew_lease in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.renew_lease] = mock_object + + request = {} + await client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.renew_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_renew_lease_async(transport: str = 'grpc_asyncio', request_type=streaming_service.RenewLeaseRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + )) + response = await client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streaming_service.RenewLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + + +@pytest.mark.asyncio +async def test_renew_lease_async_from_dict(): + await test_renew_lease_async(request_type=dict) + + +def test_renew_lease_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.RenewLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + call.return_value = streaming_service.Lease() + client.renew_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_renew_lease_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.RenewLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.renew_lease), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.Lease()) + await client.renew_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReleaseLeaseRequest, + dict, +]) +def test_release_lease(request_type, transport: str = 'grpc'): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streaming_service.ReleaseLeaseResponse( + ) + response = client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streaming_service.ReleaseLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.ReleaseLeaseResponse) + + +def test_release_lease_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 = StreamingServiceClient( + 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.release_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.release_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.ReleaseLeaseRequest() + + +def test_release_lease_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streaming_service.ReleaseLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.release_lease(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.ReleaseLeaseRequest( + id='id_value', + series='series_value', + owner='owner_value', + ) + +def test_release_lease_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.release_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.release_lease] = mock_rpc + request = {} + client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.release_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_release_lease_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.ReleaseLeaseResponse( + )) + response = await client.release_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streaming_service.ReleaseLeaseRequest() + +@pytest.mark.asyncio +async def test_release_lease_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.release_lease in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.release_lease] = mock_object + + request = {} + await client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.release_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_release_lease_async(transport: str = 'grpc_asyncio', request_type=streaming_service.ReleaseLeaseRequest): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.ReleaseLeaseResponse( + )) + response = await client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streaming_service.ReleaseLeaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.ReleaseLeaseResponse) + + +@pytest.mark.asyncio +async def test_release_lease_async_from_dict(): + await test_release_lease_async(request_type=dict) + + +def test_release_lease_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.ReleaseLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + call.return_value = streaming_service.ReleaseLeaseResponse() + client.release_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_release_lease_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streaming_service.ReleaseLeaseRequest() + + request.series = 'series_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.release_lease), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streaming_service.ReleaseLeaseResponse()) + await client.release_lease(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', + 'series=series_value', + ) in kw['metadata'] + + +def test_send_packets_rest_no_http_options(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = streaming_service.SendPacketsRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.send_packets(requests) + + +def test_receive_packets_rest_no_http_options(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = streaming_service.ReceivePacketsRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.receive_packets(requests) + + +def test_receive_events_rest_no_http_options(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = streaming_service.ReceiveEventsRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.receive_events(requests) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.AcquireLeaseRequest, + dict, +]) +def test_acquire_lease_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streaming_service.Lease.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.acquire_lease(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + +def test_acquire_lease_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acquire_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acquire_lease] = mock_rpc + + request = {} + client.acquire_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acquire_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_acquire_lease_rest_interceptors(null_interceptor): + transport = transports.StreamingServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamingServiceRestInterceptor(), + ) + client = StreamingServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "post_acquire_lease") as post, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "pre_acquire_lease") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streaming_service.AcquireLeaseRequest.pb(streaming_service.AcquireLeaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streaming_service.Lease.to_json(streaming_service.Lease()) + + request = streaming_service.AcquireLeaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streaming_service.Lease() + + client.acquire_lease(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_acquire_lease_rest_bad_request(transport: str = 'rest', request_type=streaming_service.AcquireLeaseRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.acquire_lease(request) + + +def test_acquire_lease_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.RenewLeaseRequest, + dict, +]) +def test_renew_lease_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streaming_service.Lease( + id='id_value', + series='series_value', + owner='owner_value', + lease_type=streaming_service.LeaseType.LEASE_TYPE_READER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streaming_service.Lease.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.renew_lease(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.Lease) + assert response.id == 'id_value' + assert response.series == 'series_value' + assert response.owner == 'owner_value' + assert response.lease_type == streaming_service.LeaseType.LEASE_TYPE_READER + +def test_renew_lease_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.renew_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.renew_lease] = mock_rpc + + request = {} + client.renew_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.renew_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_renew_lease_rest_interceptors(null_interceptor): + transport = transports.StreamingServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamingServiceRestInterceptor(), + ) + client = StreamingServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "post_renew_lease") as post, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "pre_renew_lease") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streaming_service.RenewLeaseRequest.pb(streaming_service.RenewLeaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streaming_service.Lease.to_json(streaming_service.Lease()) + + request = streaming_service.RenewLeaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streaming_service.Lease() + + client.renew_lease(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_renew_lease_rest_bad_request(transport: str = 'rest', request_type=streaming_service.RenewLeaseRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.renew_lease(request) + + +def test_renew_lease_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streaming_service.ReleaseLeaseRequest, + dict, +]) +def test_release_lease_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streaming_service.ReleaseLeaseResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streaming_service.ReleaseLeaseResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.release_lease(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streaming_service.ReleaseLeaseResponse) + +def test_release_lease_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.release_lease in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.release_lease] = mock_rpc + + request = {} + client.release_lease(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.release_lease(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_release_lease_rest_interceptors(null_interceptor): + transport = transports.StreamingServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamingServiceRestInterceptor(), + ) + client = StreamingServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "post_release_lease") as post, \ + mock.patch.object(transports.StreamingServiceRestInterceptor, "pre_release_lease") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streaming_service.ReleaseLeaseRequest.pb(streaming_service.ReleaseLeaseRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streaming_service.ReleaseLeaseResponse.to_json(streaming_service.ReleaseLeaseResponse()) + + request = streaming_service.ReleaseLeaseRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streaming_service.ReleaseLeaseResponse() + + client.release_lease(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_release_lease_rest_bad_request(transport: str = 'rest', request_type=streaming_service.ReleaseLeaseRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.release_lease(request) + + +def test_release_lease_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_send_packets_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.send_packets({}) + assert ( + "Method SendPackets is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_receive_packets_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.receive_packets({}) + assert ( + "Method ReceivePackets is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_receive_events_rest_error(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.receive_events({}) + assert ( + "Method ReceiveEvents is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StreamingServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StreamingServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceGrpcAsyncIOTransport, + transports.StreamingServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = StreamingServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.StreamingServiceGrpcTransport, + ) + +def test_streaming_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.StreamingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_streaming_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1alpha1.services.streaming_service.transports.StreamingServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.StreamingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'send_packets', + 'receive_packets', + 'receive_events', + 'acquire_lease', + 'renew_lease', + 'release_lease', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_streaming_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1alpha1.services.streaming_service.transports.StreamingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamingServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_streaming_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1alpha1.services.streaming_service.transports.StreamingServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamingServiceTransport() + adc.assert_called_once() + + +def test_streaming_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + StreamingServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceGrpcAsyncIOTransport, + ], +) +def test_streaming_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamingServiceGrpcTransport, + transports.StreamingServiceGrpcAsyncIOTransport, + transports.StreamingServiceRestTransport, + ], +) +def test_streaming_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.StreamingServiceGrpcTransport, grpc_helpers), + (transports.StreamingServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_streaming_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.StreamingServiceGrpcTransport, transports.StreamingServiceGrpcAsyncIOTransport]) +def test_streaming_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_streaming_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.StreamingServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streaming_service_host_no_port(transport_name): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streaming_service_host_with_port(transport_name): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_streaming_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = StreamingServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = StreamingServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.send_packets._session + session2 = client2.transport.send_packets._session + assert session1 != session2 + session1 = client1.transport.receive_packets._session + session2 = client2.transport.receive_packets._session + assert session1 != session2 + session1 = client1.transport.receive_events._session + session2 = client2.transport.receive_events._session + assert session1 != session2 + session1 = client1.transport.acquire_lease._session + session2 = client2.transport.acquire_lease._session + assert session1 != session2 + session1 = client1.transport.renew_lease._session + session2 = client2.transport.renew_lease._session + assert session1 != session2 + session1 = client1.transport.release_lease._session + session2 = client2.transport.release_lease._session + assert session1 != session2 +def test_streaming_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamingServiceGrpcTransport( + 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_streaming_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamingServiceGrpcAsyncIOTransport( + 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.StreamingServiceGrpcTransport, transports.StreamingServiceGrpcAsyncIOTransport]) +def test_streaming_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.StreamingServiceGrpcTransport, transports.StreamingServiceGrpcAsyncIOTransport]) +def test_streaming_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_series_path(): + project = "squid" + location = "clam" + cluster = "whelk" + series = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + actual = StreamingServiceClient.series_path(project, location, cluster, series) + assert expected == actual + + +def test_parse_series_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "series": "mussel", + } + path = StreamingServiceClient.series_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_series_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = StreamingServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = StreamingServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = StreamingServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = StreamingServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = StreamingServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = StreamingServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = StreamingServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = StreamingServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = StreamingServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = StreamingServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.StreamingServiceTransport, '_prep_wrapped_messages') as prep: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.StreamingServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = StreamingServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = StreamingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = StreamingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (StreamingServiceClient, transports.StreamingServiceGrpcTransport), + (StreamingServiceAsyncClient, transports.StreamingServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_streams_service.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_streams_service.py new file mode 100644 index 000000000000..ed5b47e5ce32 --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_streams_service.py @@ -0,0 +1,19007 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1alpha1.services.streams_service import StreamsServiceAsyncClient +from google.cloud.visionai_v1alpha1.services.streams_service import StreamsServiceClient +from google.cloud.visionai_v1alpha1.services.streams_service import pagers +from google.cloud.visionai_v1alpha1.services.streams_service import transports +from google.cloud.visionai_v1alpha1.types import common +from google.cloud.visionai_v1alpha1.types import streams_resources +from google.cloud.visionai_v1alpha1.types import streams_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 StreamsServiceClient._get_default_mtls_endpoint(None) is None + assert StreamsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert StreamsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert StreamsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + StreamsServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert StreamsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert StreamsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamsServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert StreamsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert StreamsServiceClient._get_client_cert_source(None, False) is None + assert StreamsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert StreamsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert StreamsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert StreamsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert StreamsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert StreamsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert StreamsServiceClient._get_api_endpoint(None, None, default_universe, "always") == StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == StreamsServiceClient.DEFAULT_MTLS_ENDPOINT + assert StreamsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert StreamsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + StreamsServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert StreamsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert StreamsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert StreamsServiceClient._get_universe_domain(None, None) == StreamsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + StreamsServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamsServiceClient, "grpc"), + (StreamsServiceAsyncClient, "grpc_asyncio"), + (StreamsServiceClient, "rest"), +]) +def test_streams_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.StreamsServiceGrpcTransport, "grpc"), + (transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.StreamsServiceRestTransport, "rest"), +]) +def test_streams_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StreamsServiceClient, "grpc"), + (StreamsServiceAsyncClient, "grpc_asyncio"), + (StreamsServiceClient, "rest"), +]) +def test_streams_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_streams_service_client_get_transport_class(): + transport = StreamsServiceClient.get_transport_class() + available_transports = [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceRestTransport, + ] + assert transport in available_transports + + transport = StreamsServiceClient.get_transport_class("grpc") + assert transport == transports.StreamsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest"), +]) +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +def test_streams_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(StreamsServiceClient, '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(StreamsServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", "true"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", "false"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest", "true"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_streams_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + StreamsServiceClient, StreamsServiceAsyncClient +]) +@mock.patch.object(StreamsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamsServiceAsyncClient)) +def test_streams_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + StreamsServiceClient, StreamsServiceAsyncClient +]) +@mock.patch.object(StreamsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceClient)) +@mock.patch.object(StreamsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StreamsServiceAsyncClient)) +def test_streams_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = StreamsServiceClient._DEFAULT_UNIVERSE + default_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StreamsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc"), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest"), +]) +def test_streams_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", grpc_helpers), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (StreamsServiceClient, transports.StreamsServiceRestTransport, "rest", None), +]) +def test_streams_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_streams_service_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1alpha1.services.streams_service.transports.StreamsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = StreamsServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport, "grpc", grpc_helpers), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_streams_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListClustersRequest, + dict, +]) +def test_list_clusters(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_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 = StreamsServiceClient( + 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_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListClustersRequest() + + +def test_list_clusters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListClustersRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_clusters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListClustersRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_clusters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc + request = {} + client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_clusters_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListClustersRequest() + +@pytest.mark.asyncio +async def test_list_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_clusters in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_clusters] = mock_object + + request = {} + await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_clusters_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListClustersRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_clusters_async_from_dict(): + await test_list_clusters_async(request_type=dict) + + +def test_list_clusters_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = streams_service.ListClustersResponse() + client.list_clusters(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_clusters_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse()) + await client.list_clusters(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_clusters_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_clusters( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_clusters_flattened_error(): + client = StreamsServiceClient( + 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_clusters( + streams_service.ListClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_clusters_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_clusters( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_clusters_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_clusters( + streams_service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_clusters(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, common.Cluster) + for i in results) +def test_list_clusters_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_clusters(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_clusters_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_clusters(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, common.Cluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_clusters_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_clusters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetClusterRequest, + dict, +]) +def test_get_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + ) + response = client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, common.Cluster) + assert response.name == 'name_value' + assert response.dataplane_service_endpoint == 'dataplane_service_endpoint_value' + assert response.state == common.Cluster.State.PROVISIONING + assert response.psc_target == 'psc_target_value' + + +def test_get_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetClusterRequest() + + +def test_get_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetClusterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetClusterRequest( + name='name_value', + ) + +def test_get_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc + request = {} + client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + )) + response = await client.get_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetClusterRequest() + +@pytest.mark.asyncio +async def test_get_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_cluster] = mock_object + + request = {} + await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + )) + response = await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, common.Cluster) + assert response.name == 'name_value' + assert response.dataplane_service_endpoint == 'dataplane_service_endpoint_value' + assert response.state == common.Cluster.State.PROVISIONING + assert response.psc_target == 'psc_target_value' + + +@pytest.mark.asyncio +async def test_get_cluster_async_from_dict(): + await test_get_cluster_async(request_type=dict) + + +def test_get_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = common.Cluster() + client.get_cluster(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_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster()) + await client.get_cluster(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_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = common.Cluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.GetClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = common.Cluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.Cluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.GetClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateClusterRequest, + dict, +]) +def test_create_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateClusterRequest() + + +def test_create_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateClusterRequest( + parent='parent_value', + cluster_id='cluster_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateClusterRequest( + parent='parent_value', + cluster_id='cluster_id_value', + request_id='request_id_value', + ) + +def test_create_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc + request = {} + client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateClusterRequest() + +@pytest.mark.asyncio +async def test_create_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_cluster] = mock_object + + request = {} + await client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_cluster_async_from_dict(): + await test_create_cluster_async(request_type=dict) + + +def test_create_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_cluster(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_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_cluster(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_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_cluster( + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.CreateClusterRequest(), + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_cluster( + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.CreateClusterRequest(), + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateClusterRequest, + dict, +]) +def test_update_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateClusterRequest() + + +def test_update_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateClusterRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateClusterRequest( + request_id='request_id_value', + ) + +def test_update_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc + request = {} + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateClusterRequest() + +@pytest.mark.asyncio +async def test_update_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_cluster] = mock_object + + request = {} + await client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_cluster_async_from_dict(): + await test_update_cluster_async(request_type=dict) + + +def test_update_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_cluster(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', + 'cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_cluster(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', + 'cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_cluster( + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.UpdateClusterRequest(), + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_cluster( + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].cluster + mock_val = common.Cluster(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.UpdateClusterRequest(), + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_cluster_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 = StreamsServiceClient( + 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_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteClusterRequest() + + +def test_delete_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteClusterRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteClusterRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc + request = {} + client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_cluster_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteClusterRequest() + +@pytest.mark.asyncio +async def test_delete_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_cluster] = mock_object + + request = {} + await client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_cluster_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteClusterRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_cluster_async_from_dict(): + await test_delete_cluster_async(request_type=dict) + + +def test_delete_cluster_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_cluster(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_cluster_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_cluster(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_cluster_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_cluster_flattened_error(): + client = StreamsServiceClient( + 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_cluster( + streams_service.DeleteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_cluster_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_cluster( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_cluster_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_cluster( + streams_service.DeleteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListStreamsRequest, + dict, +]) +def test_list_streams(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStreamsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_streams_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 = StreamsServiceClient( + 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_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListStreamsRequest() + + +def test_list_streams_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListStreamsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_streams(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListStreamsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_streams_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_streams] = mock_rpc + request = {} + client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_streams_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListStreamsRequest() + +@pytest.mark.asyncio +async def test_list_streams_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_streams in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_streams] = mock_object + + request = {} + await client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_streams_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListStreamsRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStreamsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_streams_async_from_dict(): + await test_list_streams_async(request_type=dict) + + +def test_list_streams_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + call.return_value = streams_service.ListStreamsResponse() + client.list_streams(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_streams_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse()) + await client.list_streams(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_streams_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListStreamsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_streams_flattened_error(): + client = StreamsServiceClient( + 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_streams( + streams_service.ListStreamsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_streams_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListStreamsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListStreamsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_streams_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_streams( + streams_service.ListStreamsRequest(), + parent='parent_value', + ) + + +def test_list_streams_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_streams(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Stream) + for i in results) +def test_list_streams_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + pages = list(client.list_streams(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_streams_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_streams(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, streams_resources.Stream) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_streams_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_streams(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetStreamRequest, + dict, +]) +def test_get_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + ) + response = client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Stream) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enable_hls_playback is True + assert response.media_warehouse_asset == 'media_warehouse_asset_value' + + +def test_get_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamRequest() + + +def test_get_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetStreamRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamRequest( + name='name_value', + ) + +def test_get_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_stream] = mock_rpc + request = {} + client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + )) + response = await client.get_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetStreamRequest() + +@pytest.mark.asyncio +async def test_get_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_stream] = mock_object + + request = {} + await client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + )) + response = await client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Stream) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enable_hls_playback is True + assert response.media_warehouse_asset == 'media_warehouse_asset_value' + + +@pytest.mark.asyncio +async def test_get_stream_async_from_dict(): + await test_get_stream_async(request_type=dict) + + +def test_get_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + call.return_value = streams_resources.Stream() + client.get_stream(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_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream()) + await client.get_stream(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_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Stream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.GetStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Stream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Stream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.GetStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateStreamRequest, + dict, +]) +def test_create_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateStreamRequest() + + +def test_create_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateStreamRequest( + parent='parent_value', + stream_id='stream_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateStreamRequest( + parent='parent_value', + stream_id='stream_id_value', + request_id='request_id_value', + ) + +def test_create_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_stream] = mock_rpc + request = {} + client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateStreamRequest() + +@pytest.mark.asyncio +async def test_create_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_stream] = mock_object + + request = {} + await client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_stream_async_from_dict(): + await test_create_stream_async(request_type=dict) + + +def test_create_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_stream(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_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_stream(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_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_stream( + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].stream_id + mock_val = 'stream_id_value' + assert arg == mock_val + + +def test_create_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.CreateStreamRequest(), + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + +@pytest.mark.asyncio +async def test_create_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_stream( + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].stream_id + mock_val = 'stream_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.CreateStreamRequest(), + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateStreamRequest, + dict, +]) +def test_update_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateStreamRequest() + + +def test_update_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateStreamRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateStreamRequest( + request_id='request_id_value', + ) + +def test_update_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_stream] = mock_rpc + request = {} + client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateStreamRequest() + +@pytest.mark.asyncio +async def test_update_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_stream] = mock_object + + request = {} + await client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_stream_async_from_dict(): + await test_update_stream_async(request_type=dict) + + +def test_update_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateStreamRequest() + + request.stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_stream(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', + 'stream.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateStreamRequest() + + request.stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_stream(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', + 'stream.name=name_value', + ) in kw['metadata'] + + +def test_update_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_stream( + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.UpdateStreamRequest(), + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_stream( + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = streams_resources.Stream(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.UpdateStreamRequest(), + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteStreamRequest, + dict, +]) +def test_delete_stream(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_stream_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 = StreamsServiceClient( + 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_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteStreamRequest() + + +def test_delete_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteStreamRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteStreamRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_stream] = mock_rpc + request = {} + client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteStreamRequest() + +@pytest.mark.asyncio +async def test_delete_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_stream] = mock_object + + request = {} + await client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_stream_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteStreamRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_stream_async_from_dict(): + await test_delete_stream_async(request_type=dict) + + +def test_delete_stream_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_stream(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_stream_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_stream(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_stream_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_stream_flattened_error(): + client = StreamsServiceClient( + 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_stream( + streams_service.DeleteStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_stream_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_stream_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_stream( + streams_service.DeleteStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.GenerateStreamHlsTokenRequest, + dict, +]) +def test_generate_stream_hls_token(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + ) + response = client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GenerateStreamHlsTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_service.GenerateStreamHlsTokenResponse) + assert response.token == 'token_value' + + +def test_generate_stream_hls_token_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 = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_stream_hls_token() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GenerateStreamHlsTokenRequest() + + +def test_generate_stream_hls_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GenerateStreamHlsTokenRequest( + stream='stream_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_stream_hls_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GenerateStreamHlsTokenRequest( + stream='stream_value', + ) + +def test_generate_stream_hls_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_stream_hls_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_stream_hls_token] = mock_rpc + request = {} + client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_stream_hls_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + )) + response = await client.generate_stream_hls_token() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GenerateStreamHlsTokenRequest() + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_stream_hls_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.generate_stream_hls_token] = mock_object + + request = {} + await client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.generate_stream_hls_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_async(transport: str = 'grpc_asyncio', request_type=streams_service.GenerateStreamHlsTokenRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + )) + response = await client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GenerateStreamHlsTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_service.GenerateStreamHlsTokenResponse) + assert response.token == 'token_value' + + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_async_from_dict(): + await test_generate_stream_hls_token_async(request_type=dict) + + +def test_generate_stream_hls_token_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GenerateStreamHlsTokenRequest() + + request.stream = 'stream_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value = streams_service.GenerateStreamHlsTokenResponse() + client.generate_stream_hls_token(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', + 'stream=stream_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GenerateStreamHlsTokenRequest() + + request.stream = 'stream_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse()) + await client.generate_stream_hls_token(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', + 'stream=stream_value', + ) in kw['metadata'] + + +def test_generate_stream_hls_token_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.GenerateStreamHlsTokenResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_stream_hls_token( + stream='stream_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = 'stream_value' + assert arg == mock_val + + +def test_generate_stream_hls_token_flattened_error(): + client = StreamsServiceClient( + 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.generate_stream_hls_token( + streams_service.GenerateStreamHlsTokenRequest(), + stream='stream_value', + ) + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_stream_hls_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.GenerateStreamHlsTokenResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.GenerateStreamHlsTokenResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_stream_hls_token( + stream='stream_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].stream + mock_val = 'stream_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_stream_hls_token_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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.generate_stream_hls_token( + streams_service.GenerateStreamHlsTokenRequest(), + stream='stream_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListEventsRequest, + dict, +]) +def test_list_events(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_events_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 = StreamsServiceClient( + 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_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListEventsRequest() + + +def test_list_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListEventsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListEventsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_events] = mock_rpc + request = {} + client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListEventsRequest() + +@pytest.mark.asyncio +async def test_list_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_events] = mock_object + + request = {} + await client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_events_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListEventsRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_events_async_from_dict(): + await test_list_events_async(request_type=dict) + + +def test_list_events_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + call.return_value = streams_service.ListEventsResponse() + client.list_events(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_events_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse()) + await client.list_events(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_events_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_events_flattened_error(): + client = StreamsServiceClient( + 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_events( + streams_service.ListEventsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_events_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_events_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_events( + streams_service.ListEventsRequest(), + parent='parent_value', + ) + + +def test_list_events_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_events(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Event) + for i in results) +def test_list_events_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + pages = list(client.list_events(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_events_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, streams_resources.Event) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_events_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetEventRequest, + dict, +]) +def test_get_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + ) + response = client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Event) + assert response.name == 'name_value' + assert response.alignment_clock == streams_resources.Event.Clock.CAPTURE + + +def test_get_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetEventRequest() + + +def test_get_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetEventRequest( + name='name_value', + ) + +def test_get_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event] = mock_rpc + request = {} + client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + )) + response = await client.get_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetEventRequest() + +@pytest.mark.asyncio +async def test_get_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_event] = mock_object + + request = {} + await client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + )) + response = await client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Event) + assert response.name == 'name_value' + assert response.alignment_clock == streams_resources.Event.Clock.CAPTURE + + +@pytest.mark.asyncio +async def test_get_event_async_from_dict(): + await test_get_event_async(request_type=dict) + + +def test_get_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + call.return_value = streams_resources.Event() + client.get_event(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_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event()) + await client.get_event(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_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Event() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.GetEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Event() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Event()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.GetEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateEventRequest, + dict, +]) +def test_create_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateEventRequest() + + +def test_create_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateEventRequest( + parent='parent_value', + event_id='event_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateEventRequest( + parent='parent_value', + event_id='event_id_value', + request_id='request_id_value', + ) + +def test_create_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event] = mock_rpc + request = {} + client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateEventRequest() + +@pytest.mark.asyncio +async def test_create_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_event] = mock_object + + request = {} + await client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_event_async_from_dict(): + await test_create_event_async(request_type=dict) + + +def test_create_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_event(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_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_event(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_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_event( + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].event_id + mock_val = 'event_id_value' + assert arg == mock_val + + +def test_create_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.CreateEventRequest(), + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + +@pytest.mark.asyncio +async def test_create_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_event( + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].event_id + mock_val = 'event_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.CreateEventRequest(), + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateEventRequest, + dict, +]) +def test_update_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateEventRequest() + + +def test_update_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateEventRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateEventRequest( + request_id='request_id_value', + ) + +def test_update_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event] = mock_rpc + request = {} + client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateEventRequest() + +@pytest.mark.asyncio +async def test_update_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_event] = mock_object + + request = {} + await client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_event_async_from_dict(): + await test_update_event_async(request_type=dict) + + +def test_update_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateEventRequest() + + request.event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_event(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', + 'event.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateEventRequest() + + request.event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_event(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', + 'event.name=name_value', + ) in kw['metadata'] + + +def test_update_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_event( + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.UpdateEventRequest(), + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_event( + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].event + mock_val = streams_resources.Event(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.UpdateEventRequest(), + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteEventRequest, + dict, +]) +def test_delete_event(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_event_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 = StreamsServiceClient( + 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_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteEventRequest() + + +def test_delete_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteEventRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteEventRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event] = mock_rpc + request = {} + client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteEventRequest() + +@pytest.mark.asyncio +async def test_delete_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_event] = mock_object + + request = {} + await client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteEventRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_event_async_from_dict(): + await test_delete_event_async(request_type=dict) + + +def test_delete_event_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_event(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_event_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_event(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_event_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_event_flattened_error(): + client = StreamsServiceClient( + 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_event( + streams_service.DeleteEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_event_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_event_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_event( + streams_service.DeleteEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListSeriesRequest, + dict, +]) +def test_list_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.ListSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSeriesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListSeriesRequest() + + +def test_list_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.ListSeriesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListSeriesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_series] = mock_rpc + request = {} + client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.ListSeriesRequest() + +@pytest.mark.asyncio +async def test_list_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_series] = mock_object + + request = {} + await client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.ListSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.ListSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSeriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_series_async_from_dict(): + await test_list_series_async(request_type=dict) + + +def test_list_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + call.return_value = streams_service.ListSeriesResponse() + client.list_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.ListSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse()) + await client.list_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListSeriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_series( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.ListSeriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_service.ListSeriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_service.ListSeriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_series( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.ListSeriesRequest(), + parent='parent_value', + ) + + +def test_list_series_pager(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_series(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Series) + for i in results) +def test_list_series_pages(transport_name: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + pages = list(client.list_series(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_series_async_pager(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_series(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, streams_resources.Series) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_series_async_pages(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_series), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_series(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + streams_service.GetSeriesRequest, + dict, +]) +def test_get_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + ) + response = client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.GetSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Series) + assert response.name == 'name_value' + assert response.stream == 'stream_value' + assert response.event == 'event_value' + + +def test_get_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetSeriesRequest() + + +def test_get_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.GetSeriesRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetSeriesRequest( + name='name_value', + ) + +def test_get_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_series] = mock_rpc + request = {} + client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + )) + response = await client.get_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.GetSeriesRequest() + +@pytest.mark.asyncio +async def test_get_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_series] = mock_object + + request = {} + await client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.GetSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + )) + response = await client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.GetSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Series) + assert response.name == 'name_value' + assert response.stream == 'stream_value' + assert response.event == 'event_value' + + +@pytest.mark.asyncio +async def test_get_series_async_from_dict(): + await test_get_series_async(request_type=dict) + + +def test_get_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + call.return_value = streams_resources.Series() + client.get_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.GetSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series()) + await client.get_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Series() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.GetSeriesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = streams_resources.Series() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(streams_resources.Series()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.GetSeriesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateSeriesRequest, + dict, +]) +def test_create_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.CreateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateSeriesRequest() + + +def test_create_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.CreateSeriesRequest( + parent='parent_value', + series_id='series_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateSeriesRequest( + parent='parent_value', + series_id='series_id_value', + request_id='request_id_value', + ) + +def test_create_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_series] = mock_rpc + request = {} + client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.CreateSeriesRequest() + +@pytest.mark.asyncio +async def test_create_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_series] = mock_object + + request = {} + await client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.CreateSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.CreateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_series_async_from_dict(): + await test_create_series_async(request_type=dict) + + +def test_create_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.CreateSeriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_series( + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].series_id + mock_val = 'series_id_value' + assert arg == mock_val + + +def test_create_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.CreateSeriesRequest(), + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + +@pytest.mark.asyncio +async def test_create_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_series( + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].series_id + mock_val = 'series_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.CreateSeriesRequest(), + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateSeriesRequest, + dict, +]) +def test_update_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateSeriesRequest() + + +def test_update_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.UpdateSeriesRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateSeriesRequest( + request_id='request_id_value', + ) + +def test_update_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_series] = mock_rpc + request = {} + client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.UpdateSeriesRequest() + +@pytest.mark.asyncio +async def test_update_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_series] = mock_object + + request = {} + await client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.UpdateSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.UpdateSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_series_async_from_dict(): + await test_update_series_async(request_type=dict) + + +def test_update_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateSeriesRequest() + + request.series.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_series(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', + 'series.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.UpdateSeriesRequest() + + request.series.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_series(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', + 'series.name=name_value', + ) in kw['metadata'] + + +def test_update_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_series( + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.UpdateSeriesRequest(), + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_series( + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].series + mock_val = streams_resources.Series(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.UpdateSeriesRequest(), + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteSeriesRequest, + dict, +]) +def test_delete_series(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_series_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 = StreamsServiceClient( + 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_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteSeriesRequest() + + +def test_delete_series_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.DeleteSeriesRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_series(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteSeriesRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_series_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_series] = mock_rpc + request = {} + client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_series_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_series() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.DeleteSeriesRequest() + +@pytest.mark.asyncio +async def test_delete_series_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_series in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_series] = mock_object + + request = {} + await client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_series_async(transport: str = 'grpc_asyncio', request_type=streams_service.DeleteSeriesRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.DeleteSeriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_series_async_from_dict(): + await test_delete_series_async(request_type=dict) + + +def test_delete_series_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_series(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_series_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.DeleteSeriesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_series(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_series_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_series_flattened_error(): + client = StreamsServiceClient( + 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_series( + streams_service.DeleteSeriesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_series_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_series), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_series( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_series_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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_series( + streams_service.DeleteSeriesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.MaterializeChannelRequest, + dict, +]) +def test_materialize_channel(request_type, transport: str = 'grpc'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = streams_service.MaterializeChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_materialize_channel_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 = StreamsServiceClient( + 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.materialize_channel), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.materialize_channel() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.MaterializeChannelRequest() + + +def test_materialize_channel_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = streams_service.MaterializeChannelRequest( + parent='parent_value', + channel_id='channel_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.materialize_channel(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.MaterializeChannelRequest( + parent='parent_value', + channel_id='channel_id_value', + request_id='request_id_value', + ) + +def test_materialize_channel_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.materialize_channel in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.materialize_channel] = mock_rpc + request = {} + client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.materialize_channel(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_materialize_channel_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.materialize_channel() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == streams_service.MaterializeChannelRequest() + +@pytest.mark.asyncio +async def test_materialize_channel_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.materialize_channel in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.materialize_channel] = mock_object + + request = {} + await client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.materialize_channel(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_materialize_channel_async(transport: str = 'grpc_asyncio', request_type=streams_service.MaterializeChannelRequest): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = streams_service.MaterializeChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_materialize_channel_async_from_dict(): + await test_materialize_channel_async(request_type=dict) + + +def test_materialize_channel_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.MaterializeChannelRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.materialize_channel(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_materialize_channel_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = streams_service.MaterializeChannelRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.materialize_channel(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_materialize_channel_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.materialize_channel( + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].channel + mock_val = streams_resources.Channel(name='name_value') + assert arg == mock_val + arg = args[0].channel_id + mock_val = 'channel_id_value' + assert arg == mock_val + + +def test_materialize_channel_flattened_error(): + client = StreamsServiceClient( + 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.materialize_channel( + streams_service.MaterializeChannelRequest(), + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + +@pytest.mark.asyncio +async def test_materialize_channel_flattened_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.materialize_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.materialize_channel( + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].channel + mock_val = streams_resources.Channel(name='name_value') + assert arg == mock_val + arg = args[0].channel_id + mock_val = 'channel_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_materialize_channel_flattened_error_async(): + client = StreamsServiceAsyncClient( + 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.materialize_channel( + streams_service.MaterializeChannelRequest(), + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListClustersRequest, + dict, +]) +def test_list_clusters_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc + + request = {} + client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_clusters_rest_required_fields(request_type=streams_service.ListClustersRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_clusters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_clusters_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_clusters") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListClustersRequest.pb(streams_service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListClustersResponse.to_json(streams_service.ListClustersResponse()) + + request = streams_service.ListClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListClustersResponse() + + client.list_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListClustersRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_clusters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/clusters" % client.transport._host, args[1]) + + +def test_list_clusters_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_clusters( + streams_service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + common.Cluster(), + ], + next_page_token='abc', + ), + streams_service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + ], + next_page_token='ghi', + ), + streams_service.ListClustersResponse( + clusters=[ + common.Cluster(), + common.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListClustersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, common.Cluster) + for i in results) + + pages = list(client.list_clusters(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetClusterRequest, + dict, +]) +def test_get_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = common.Cluster( + name='name_value', + dataplane_service_endpoint='dataplane_service_endpoint_value', + state=common.Cluster.State.PROVISIONING, + psc_target='psc_target_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = common.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.Cluster) + assert response.name == 'name_value' + assert response.dataplane_service_endpoint == 'dataplane_service_endpoint_value' + assert response.state == common.Cluster.State.PROVISIONING + assert response.psc_target == 'psc_target_value' + +def test_get_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc + + request = {} + client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_cluster_rest_required_fields(request_type=streams_service.GetClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = common.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetClusterRequest.pb(streams_service.GetClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = common.Cluster.to_json(common.Cluster()) + + request = streams_service.GetClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.Cluster() + + client.get_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_cluster(request) + + +def test_get_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = common.Cluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = common.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_get_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_cluster( + streams_service.GetClusterRequest(), + name='name_value', + ) + + +def test_get_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateClusterRequest, + dict, +]) +def test_create_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'dataplane_service_endpoint': 'dataplane_service_endpoint_value', 'state': 1, 'psc_target': 'psc_target_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc + + request = {} + client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_cluster_rest_required_fields(request_type=streams_service.CreateClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateClusterRequest.pb(streams_service.CreateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_cluster(request) + + +def test_create_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/clusters" % client.transport._host, args[1]) + + +def test_create_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_cluster( + streams_service.CreateClusterRequest(), + parent='parent_value', + cluster=common.Cluster(name='name_value'), + cluster_id='cluster_id_value', + ) + + +def test_create_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateClusterRequest, + dict, +]) +def test_update_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'dataplane_service_endpoint': 'dataplane_service_endpoint_value', 'state': 1, 'psc_target': 'psc_target_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc + + request = {} + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_cluster_rest_required_fields(request_type=streams_service.UpdateClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateClusterRequest.pb(streams_service.UpdateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_cluster(request) + + +def test_update_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{cluster.name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_update_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_cluster( + streams_service.UpdateClusterRequest(), + cluster=common.Cluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc + + request = {} + client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_cluster_rest_required_fields(request_type=streams_service.DeleteClusterRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_cluster_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_cluster_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_cluster") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteClusterRequest.pb(streams_service.DeleteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_cluster_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteClusterRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_cluster(request) + + +def test_delete_cluster_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_delete_cluster_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_cluster( + streams_service.DeleteClusterRequest(), + name='name_value', + ) + + +def test_delete_cluster_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListStreamsRequest, + dict, +]) +def test_list_streams_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListStreamsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_streams(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStreamsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_streams_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_streams] = mock_rpc + + request = {} + client.list_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_streams_rest_required_fields(request_type=streams_service.ListStreamsRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_streams._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_streams._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListStreamsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_streams(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_streams_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_streams._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_streams_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_streams") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_streams") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListStreamsRequest.pb(streams_service.ListStreamsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListStreamsResponse.to_json(streams_service.ListStreamsResponse()) + + request = streams_service.ListStreamsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListStreamsResponse() + + client.list_streams(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_streams_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListStreamsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_streams(request) + + +def test_list_streams_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListStreamsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_streams(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/streams" % client.transport._host, args[1]) + + +def test_list_streams_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_streams( + streams_service.ListStreamsRequest(), + parent='parent_value', + ) + + +def test_list_streams_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + streams_resources.Stream(), + ], + next_page_token='abc', + ), + streams_service.ListStreamsResponse( + streams=[], + next_page_token='def', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + ], + next_page_token='ghi', + ), + streams_service.ListStreamsResponse( + streams=[ + streams_resources.Stream(), + streams_resources.Stream(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListStreamsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_streams(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Stream) + for i in results) + + pages = list(client.list_streams(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetStreamRequest, + dict, +]) +def test_get_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Stream( + name='name_value', + display_name='display_name_value', + enable_hls_playback=True, + media_warehouse_asset='media_warehouse_asset_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Stream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Stream) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enable_hls_playback is True + assert response.media_warehouse_asset == 'media_warehouse_asset_value' + +def test_get_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_stream] = mock_rpc + + request = {} + client.get_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_stream_rest_required_fields(request_type=streams_service.GetStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_resources.Stream() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_resources.Stream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetStreamRequest.pb(streams_service.GetStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_resources.Stream.to_json(streams_resources.Stream()) + + request = streams_service.GetStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_resources.Stream() + + client.get_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_stream(request) + + +def test_get_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Stream() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Stream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/streams/*}" % client.transport._host, args[1]) + + +def test_get_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_stream( + streams_service.GetStreamRequest(), + name='name_value', + ) + + +def test_get_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateStreamRequest, + dict, +]) +def test_create_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["stream"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'enable_hls_playback': True, 'media_warehouse_asset': 'media_warehouse_asset_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateStreamRequest.meta.fields["stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["stream"][field])): + del request_init["stream"][field][i][subfield] + else: + del request_init["stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_stream(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_stream] = mock_rpc + + request = {} + client.create_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_stream_rest_required_fields(request_type=streams_service.CreateStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["stream_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "streamId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "streamId" in jsonified_request + assert jsonified_request["streamId"] == request_init["stream_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["streamId"] = 'stream_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_stream._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "stream_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "streamId" in jsonified_request + assert jsonified_request["streamId"] == 'stream_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_stream(request) + + expected_params = [ + ( + "streamId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "streamId", )) & set(("parent", "streamId", "stream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateStreamRequest.pb(streams_service.CreateStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_stream(request) + + +def test_create_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/streams" % client.transport._host, args[1]) + + +def test_create_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_stream( + streams_service.CreateStreamRequest(), + parent='parent_value', + stream=streams_resources.Stream(name='name_value'), + stream_id='stream_id_value', + ) + + +def test_create_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateStreamRequest, + dict, +]) +def test_update_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'stream': {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'}} + request_init["stream"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'enable_hls_playback': True, 'media_warehouse_asset': 'media_warehouse_asset_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateStreamRequest.meta.fields["stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["stream"][field])): + del request_init["stream"][field][i][subfield] + else: + del request_init["stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_stream(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_stream] = mock_rpc + + request = {} + client.update_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_stream_rest_required_fields(request_type=streams_service.UpdateStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_stream._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "stream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateStreamRequest.pb(streams_service.UpdateStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'stream': {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_stream(request) + + +def test_update_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'stream': {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{stream.name=projects/*/locations/*/clusters/*/streams/*}" % client.transport._host, args[1]) + + +def test_update_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_stream( + streams_service.UpdateStreamRequest(), + stream=streams_resources.Stream(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteStreamRequest, + dict, +]) +def test_delete_stream_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_stream(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_stream] = mock_rpc + + request = {} + client.delete_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_stream_rest_required_fields(request_type=streams_service.DeleteStreamRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_stream._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_stream_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_stream_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_stream") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteStreamRequest.pb(streams_service.DeleteStreamRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_stream_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteStreamRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_stream(request) + + +def test_delete_stream_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/streams/*}" % client.transport._host, args[1]) + + +def test_delete_stream_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_stream( + streams_service.DeleteStreamRequest(), + name='name_value', + ) + + +def test_delete_stream_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.GenerateStreamHlsTokenRequest, + dict, +]) +def test_generate_stream_hls_token_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.GenerateStreamHlsTokenResponse( + token='token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.GenerateStreamHlsTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_stream_hls_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_service.GenerateStreamHlsTokenResponse) + assert response.token == 'token_value' + +def test_generate_stream_hls_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_stream_hls_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_stream_hls_token] = mock_rpc + + request = {} + client.generate_stream_hls_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_stream_hls_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_stream_hls_token_rest_required_fields(request_type=streams_service.GenerateStreamHlsTokenRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["stream"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_stream_hls_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["stream"] = 'stream_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_stream_hls_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "stream" in jsonified_request + assert jsonified_request["stream"] == 'stream_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.GenerateStreamHlsTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.GenerateStreamHlsTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.generate_stream_hls_token(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_stream_hls_token_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_stream_hls_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("stream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_stream_hls_token_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_generate_stream_hls_token") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_generate_stream_hls_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GenerateStreamHlsTokenRequest.pb(streams_service.GenerateStreamHlsTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.GenerateStreamHlsTokenResponse.to_json(streams_service.GenerateStreamHlsTokenResponse()) + + request = streams_service.GenerateStreamHlsTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.GenerateStreamHlsTokenResponse() + + client.generate_stream_hls_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_stream_hls_token_rest_bad_request(transport: str = 'rest', request_type=streams_service.GenerateStreamHlsTokenRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_stream_hls_token(request) + + +def test_generate_stream_hls_token_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.GenerateStreamHlsTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'stream': 'projects/sample1/locations/sample2/clusters/sample3/streams/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + stream='stream_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.GenerateStreamHlsTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.generate_stream_hls_token(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{stream=projects/*/locations/*/clusters/*/streams/*}:generateStreamHlsToken" % client.transport._host, args[1]) + + +def test_generate_stream_hls_token_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_stream_hls_token( + streams_service.GenerateStreamHlsTokenRequest(), + stream='stream_value', + ) + + +def test_generate_stream_hls_token_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListEventsRequest, + dict, +]) +def test_list_events_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListEventsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_events] = mock_rpc + + request = {} + client.list_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_events_rest_required_fields(request_type=streams_service.ListEventsRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListEventsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_events_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_events_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_events") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListEventsRequest.pb(streams_service.ListEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListEventsResponse.to_json(streams_service.ListEventsResponse()) + + request = streams_service.ListEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListEventsResponse() + + client.list_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_events_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListEventsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_events(request) + + +def test_list_events_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/events" % client.transport._host, args[1]) + + +def test_list_events_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_events( + streams_service.ListEventsRequest(), + parent='parent_value', + ) + + +def test_list_events_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + streams_resources.Event(), + ], + next_page_token='abc', + ), + streams_service.ListEventsResponse( + events=[], + next_page_token='def', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + ], + next_page_token='ghi', + ), + streams_service.ListEventsResponse( + events=[ + streams_resources.Event(), + streams_resources.Event(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListEventsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Event) + for i in results) + + pages = list(client.list_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetEventRequest, + dict, +]) +def test_get_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Event( + name='name_value', + alignment_clock=streams_resources.Event.Clock.CAPTURE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Event.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Event) + assert response.name == 'name_value' + assert response.alignment_clock == streams_resources.Event.Clock.CAPTURE + +def test_get_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event] = mock_rpc + + request = {} + client.get_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_event_rest_required_fields(request_type=streams_service.GetEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_resources.Event() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_resources.Event.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetEventRequest.pb(streams_service.GetEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_resources.Event.to_json(streams_resources.Event()) + + request = streams_service.GetEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_resources.Event() + + client.get_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_event(request) + + +def test_get_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Event() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Event.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/events/*}" % client.transport._host, args[1]) + + +def test_get_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_event( + streams_service.GetEventRequest(), + name='name_value', + ) + + +def test_get_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateEventRequest, + dict, +]) +def test_create_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["event"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'alignment_clock': 1, 'grace_period': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateEventRequest.meta.fields["event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event"][field])): + del request_init["event"][field][i][subfield] + else: + del request_init["event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_event(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event] = mock_rpc + + request = {} + client.create_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_event_rest_required_fields(request_type=streams_service.CreateEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["event_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "eventId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "eventId" in jsonified_request + assert jsonified_request["eventId"] == request_init["event_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["eventId"] = 'event_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("event_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "eventId" in jsonified_request + assert jsonified_request["eventId"] == 'event_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_event(request) + + expected_params = [ + ( + "eventId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("eventId", "requestId", )) & set(("parent", "eventId", "event", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateEventRequest.pb(streams_service.CreateEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_event(request) + + +def test_create_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/events" % client.transport._host, args[1]) + + +def test_create_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_event( + streams_service.CreateEventRequest(), + parent='parent_value', + event=streams_resources.Event(name='name_value'), + event_id='event_id_value', + ) + + +def test_create_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateEventRequest, + dict, +]) +def test_update_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'event': {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'}} + request_init["event"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'alignment_clock': 1, 'grace_period': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateEventRequest.meta.fields["event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event"][field])): + del request_init["event"][field][i][subfield] + else: + del request_init["event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_event(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event] = mock_rpc + + request = {} + client.update_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_event_rest_required_fields(request_type=streams_service.UpdateEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "event", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateEventRequest.pb(streams_service.UpdateEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'event': {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_event(request) + + +def test_update_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'event': {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{event.name=projects/*/locations/*/clusters/*/events/*}" % client.transport._host, args[1]) + + +def test_update_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_event( + streams_service.UpdateEventRequest(), + event=streams_resources.Event(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteEventRequest, + dict, +]) +def test_delete_event_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_event(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event] = mock_rpc + + request = {} + client.delete_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_event_rest_required_fields(request_type=streams_service.DeleteEventRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_event_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_event_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_event") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteEventRequest.pb(streams_service.DeleteEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_event_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteEventRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_event(request) + + +def test_delete_event_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/events/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/events/*}" % client.transport._host, args[1]) + + +def test_delete_event_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_event( + streams_service.DeleteEventRequest(), + name='name_value', + ) + + +def test_delete_event_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.ListSeriesRequest, + dict, +]) +def test_list_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListSeriesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListSeriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_series(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSeriesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + +def test_list_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_series] = mock_rpc + + request = {} + client.list_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_series_rest_required_fields(request_type=streams_service.ListSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_service.ListSeriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_service.ListSeriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_list_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_list_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.ListSeriesRequest.pb(streams_service.ListSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_service.ListSeriesResponse.to_json(streams_service.ListSeriesResponse()) + + request = streams_service.ListSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_service.ListSeriesResponse() + + client.list_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.ListSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_series(request) + + +def test_list_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_service.ListSeriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_service.ListSeriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/series" % client.transport._host, args[1]) + + +def test_list_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_series( + streams_service.ListSeriesRequest(), + parent='parent_value', + ) + + +def test_list_series_rest_pager(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + streams_resources.Series(), + ], + next_page_token='abc', + ), + streams_service.ListSeriesResponse( + series=[], + next_page_token='def', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + ], + next_page_token='ghi', + ), + streams_service.ListSeriesResponse( + series=[ + streams_resources.Series(), + streams_resources.Series(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(streams_service.ListSeriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + pager = client.list_series(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, streams_resources.Series) + for i in results) + + pages = list(client.list_series(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + streams_service.GetSeriesRequest, + dict, +]) +def test_get_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Series( + name='name_value', + stream='stream_value', + event='event_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Series.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_series(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, streams_resources.Series) + assert response.name == 'name_value' + assert response.stream == 'stream_value' + assert response.event == 'event_value' + +def test_get_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_series] = mock_rpc + + request = {} + client.get_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_series_rest_required_fields(request_type=streams_service.GetSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = streams_resources.Series() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = streams_resources.Series.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_get_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_get_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.GetSeriesRequest.pb(streams_service.GetSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = streams_resources.Series.to_json(streams_resources.Series()) + + request = streams_service.GetSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = streams_resources.Series() + + client.get_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.GetSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_series(request) + + +def test_get_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = streams_resources.Series() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = streams_resources.Series.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/series/*}" % client.transport._host, args[1]) + + +def test_get_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_series( + streams_service.GetSeriesRequest(), + name='name_value', + ) + + +def test_get_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.CreateSeriesRequest, + dict, +]) +def test_create_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["series"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'stream': 'stream_value', 'event': 'event_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.CreateSeriesRequest.meta.fields["series"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["series"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["series"][field])): + del request_init["series"][field][i][subfield] + else: + del request_init["series"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_series(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_series] = mock_rpc + + request = {} + client.create_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_series_rest_required_fields(request_type=streams_service.CreateSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["series_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "seriesId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "seriesId" in jsonified_request + assert jsonified_request["seriesId"] == request_init["series_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["seriesId"] = 'series_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "series_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "seriesId" in jsonified_request + assert jsonified_request["seriesId"] == 'series_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_series(request) + + expected_params = [ + ( + "seriesId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "seriesId", )) & set(("parent", "seriesId", "series", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_create_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_create_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.CreateSeriesRequest.pb(streams_service.CreateSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.CreateSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.CreateSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_series(request) + + +def test_create_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/series" % client.transport._host, args[1]) + + +def test_create_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_series( + streams_service.CreateSeriesRequest(), + parent='parent_value', + series=streams_resources.Series(name='name_value'), + series_id='series_id_value', + ) + + +def test_create_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.UpdateSeriesRequest, + dict, +]) +def test_update_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'series': {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'}} + request_init["series"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'stream': 'stream_value', 'event': 'event_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.UpdateSeriesRequest.meta.fields["series"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["series"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["series"][field])): + del request_init["series"][field][i][subfield] + else: + del request_init["series"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_series(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_update_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_series] = mock_rpc + + request = {} + client.update_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_series_rest_required_fields(request_type=streams_service.UpdateSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("updateMask", "series", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_update_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_update_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.UpdateSeriesRequest.pb(streams_service.UpdateSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.UpdateSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.UpdateSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'series': {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_series(request) + + +def test_update_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'series': {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{series.name=projects/*/locations/*/clusters/*/series/*}" % client.transport._host, args[1]) + + +def test_update_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_series( + streams_service.UpdateSeriesRequest(), + series=streams_resources.Series(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.DeleteSeriesRequest, + dict, +]) +def test_delete_series_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_series(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_series_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_series in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_series] = mock_rpc + + request = {} + client.delete_series(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_series(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_series_rest_required_fields(request_type=streams_service.DeleteSeriesRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_series._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_series._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_series(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_series_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_series._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_series_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_delete_series") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_delete_series") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.DeleteSeriesRequest.pb(streams_service.DeleteSeriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.DeleteSeriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_series(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_series_rest_bad_request(transport: str = 'rest', request_type=streams_service.DeleteSeriesRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_series(request) + + +def test_delete_series_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/series/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_series(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clusters/*/series/*}" % client.transport._host, args[1]) + + +def test_delete_series_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_series( + streams_service.DeleteSeriesRequest(), + name='name_value', + ) + + +def test_delete_series_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + streams_service.MaterializeChannelRequest, + dict, +]) +def test_materialize_channel_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["channel"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'stream': 'stream_value', 'event': 'event_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = streams_service.MaterializeChannelRequest.meta.fields["channel"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["channel"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["channel"][field])): + del request_init["channel"][field][i][subfield] + else: + del request_init["channel"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.materialize_channel(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_materialize_channel_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.materialize_channel in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.materialize_channel] = mock_rpc + + request = {} + client.materialize_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.materialize_channel(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_materialize_channel_rest_required_fields(request_type=streams_service.MaterializeChannelRequest): + transport_class = transports.StreamsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["channel_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "channelId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).materialize_channel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == request_init["channel_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["channelId"] = 'channel_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).materialize_channel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("channel_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == 'channel_id_value' + + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.materialize_channel(request) + + expected_params = [ + ( + "channelId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_materialize_channel_rest_unset_required_fields(): + transport = transports.StreamsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.materialize_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(("channelId", "requestId", )) & set(("parent", "channelId", "channel", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_materialize_channel_rest_interceptors(null_interceptor): + transport = transports.StreamsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StreamsServiceRestInterceptor(), + ) + client = StreamsServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "post_materialize_channel") as post, \ + mock.patch.object(transports.StreamsServiceRestInterceptor, "pre_materialize_channel") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = streams_service.MaterializeChannelRequest.pb(streams_service.MaterializeChannelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = streams_service.MaterializeChannelRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.materialize_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_materialize_channel_rest_bad_request(transport: str = 'rest', request_type=streams_service.MaterializeChannelRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.materialize_channel(request) + + +def test_materialize_channel_rest_flattened(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.materialize_channel(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/clusters/*}/channels" % client.transport._host, args[1]) + + +def test_materialize_channel_rest_flattened_error(transport: str = 'rest'): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.materialize_channel( + streams_service.MaterializeChannelRequest(), + parent='parent_value', + channel=streams_resources.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + +def test_materialize_channel_rest_error(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StreamsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StreamsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceGrpcAsyncIOTransport, + transports.StreamsServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = StreamsServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.StreamsServiceGrpcTransport, + ) + +def test_streams_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.StreamsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_streams_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1alpha1.services.streams_service.transports.StreamsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.StreamsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_clusters', + 'get_cluster', + 'create_cluster', + 'update_cluster', + 'delete_cluster', + 'list_streams', + 'get_stream', + 'create_stream', + 'update_stream', + 'delete_stream', + 'generate_stream_hls_token', + 'list_events', + 'get_event', + 'create_event', + 'update_event', + 'delete_event', + 'list_series', + 'get_series', + 'create_series', + 'update_series', + 'delete_series', + 'materialize_channel', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_streams_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1alpha1.services.streams_service.transports.StreamsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_streams_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1alpha1.services.streams_service.transports.StreamsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamsServiceTransport() + adc.assert_called_once() + + +def test_streams_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + StreamsServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceGrpcAsyncIOTransport, + ], +) +def test_streams_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamsServiceGrpcTransport, + transports.StreamsServiceGrpcAsyncIOTransport, + transports.StreamsServiceRestTransport, + ], +) +def test_streams_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.StreamsServiceGrpcTransport, grpc_helpers), + (transports.StreamsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_streams_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.StreamsServiceGrpcTransport, transports.StreamsServiceGrpcAsyncIOTransport]) +def test_streams_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_streams_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.StreamsServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_streams_service_rest_lro_client(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streams_service_host_no_port(transport_name): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_streams_service_host_with_port(transport_name): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_streams_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = StreamsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = StreamsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_clusters._session + session2 = client2.transport.list_clusters._session + assert session1 != session2 + session1 = client1.transport.get_cluster._session + session2 = client2.transport.get_cluster._session + assert session1 != session2 + session1 = client1.transport.create_cluster._session + session2 = client2.transport.create_cluster._session + assert session1 != session2 + session1 = client1.transport.update_cluster._session + session2 = client2.transport.update_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_cluster._session + session2 = client2.transport.delete_cluster._session + assert session1 != session2 + session1 = client1.transport.list_streams._session + session2 = client2.transport.list_streams._session + assert session1 != session2 + session1 = client1.transport.get_stream._session + session2 = client2.transport.get_stream._session + assert session1 != session2 + session1 = client1.transport.create_stream._session + session2 = client2.transport.create_stream._session + assert session1 != session2 + session1 = client1.transport.update_stream._session + session2 = client2.transport.update_stream._session + assert session1 != session2 + session1 = client1.transport.delete_stream._session + session2 = client2.transport.delete_stream._session + assert session1 != session2 + session1 = client1.transport.generate_stream_hls_token._session + session2 = client2.transport.generate_stream_hls_token._session + assert session1 != session2 + session1 = client1.transport.list_events._session + session2 = client2.transport.list_events._session + assert session1 != session2 + session1 = client1.transport.get_event._session + session2 = client2.transport.get_event._session + assert session1 != session2 + session1 = client1.transport.create_event._session + session2 = client2.transport.create_event._session + assert session1 != session2 + session1 = client1.transport.update_event._session + session2 = client2.transport.update_event._session + assert session1 != session2 + session1 = client1.transport.delete_event._session + session2 = client2.transport.delete_event._session + assert session1 != session2 + session1 = client1.transport.list_series._session + session2 = client2.transport.list_series._session + assert session1 != session2 + session1 = client1.transport.get_series._session + session2 = client2.transport.get_series._session + assert session1 != session2 + session1 = client1.transport.create_series._session + session2 = client2.transport.create_series._session + assert session1 != session2 + session1 = client1.transport.update_series._session + session2 = client2.transport.update_series._session + assert session1 != session2 + session1 = client1.transport.delete_series._session + session2 = client2.transport.delete_series._session + assert session1 != session2 + session1 = client1.transport.materialize_channel._session + session2 = client2.transport.materialize_channel._session + assert session1 != session2 +def test_streams_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamsServiceGrpcTransport( + 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_streams_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamsServiceGrpcAsyncIOTransport( + 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.StreamsServiceGrpcTransport, transports.StreamsServiceGrpcAsyncIOTransport]) +def test_streams_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.StreamsServiceGrpcTransport, transports.StreamsServiceGrpcAsyncIOTransport]) +def test_streams_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_streams_service_grpc_lro_client(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_streams_service_grpc_lro_async_client(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_channel_path(): + project = "squid" + location = "clam" + cluster = "whelk" + channel = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/channels/{channel}".format(project=project, location=location, cluster=cluster, channel=channel, ) + actual = StreamsServiceClient.channel_path(project, location, cluster, channel) + assert expected == actual + + +def test_parse_channel_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "channel": "mussel", + } + path = StreamsServiceClient.channel_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_channel_path(path) + assert expected == actual + +def test_cluster_path(): + project = "winkle" + location = "nautilus" + cluster = "scallop" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = StreamsServiceClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "abalone", + "location": "squid", + "cluster": "clam", + } + path = StreamsServiceClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_cluster_path(path) + assert expected == actual + +def test_event_path(): + project = "whelk" + location = "octopus" + cluster = "oyster" + event = "nudibranch" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/events/{event}".format(project=project, location=location, cluster=cluster, event=event, ) + actual = StreamsServiceClient.event_path(project, location, cluster, event) + assert expected == actual + + +def test_parse_event_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "cluster": "winkle", + "event": "nautilus", + } + path = StreamsServiceClient.event_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_event_path(path) + assert expected == actual + +def test_series_path(): + project = "scallop" + location = "abalone" + cluster = "squid" + series = "clam" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/series/{series}".format(project=project, location=location, cluster=cluster, series=series, ) + actual = StreamsServiceClient.series_path(project, location, cluster, series) + assert expected == actual + + +def test_parse_series_path(): + expected = { + "project": "whelk", + "location": "octopus", + "cluster": "oyster", + "series": "nudibranch", + } + path = StreamsServiceClient.series_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_series_path(path) + assert expected == actual + +def test_stream_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + stream = "nautilus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/streams/{stream}".format(project=project, location=location, cluster=cluster, stream=stream, ) + actual = StreamsServiceClient.stream_path(project, location, cluster, stream) + assert expected == actual + + +def test_parse_stream_path(): + expected = { + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "stream": "clam", + } + path = StreamsServiceClient.stream_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_stream_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = StreamsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = StreamsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = StreamsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = StreamsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = StreamsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = StreamsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = StreamsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = StreamsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = StreamsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = StreamsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = StreamsServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.StreamsServiceTransport, '_prep_wrapped_messages') as prep: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.StreamsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = StreamsServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = StreamsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = StreamsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (StreamsServiceClient, transports.StreamsServiceGrpcTransport), + (StreamsServiceAsyncClient, transports.StreamsServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_warehouse.py b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_warehouse.py new file mode 100644 index 000000000000..959319f2c07d --- /dev/null +++ b/owl-bot-staging/google-cloud-visionai/v1alpha1/tests/unit/gapic/visionai_v1alpha1/test_warehouse.py @@ -0,0 +1,22749 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.visionai_v1alpha1.services.warehouse import WarehouseAsyncClient +from google.cloud.visionai_v1alpha1.services.warehouse import WarehouseClient +from google.cloud.visionai_v1alpha1.services.warehouse import pagers +from google.cloud.visionai_v1alpha1.services.warehouse import transports +from google.cloud.visionai_v1alpha1.types import warehouse +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 WarehouseClient._get_default_mtls_endpoint(None) is None + assert WarehouseClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WarehouseClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert WarehouseClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WarehouseClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WarehouseClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + WarehouseClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert WarehouseClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WarehouseClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WarehouseClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WarehouseClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert WarehouseClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert WarehouseClient._get_client_cert_source(None, False) is None + assert WarehouseClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert WarehouseClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert WarehouseClient._get_client_cert_source(None, True) is mock_default_cert_source + assert WarehouseClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WarehouseClient._DEFAULT_UNIVERSE + default_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert WarehouseClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert WarehouseClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == WarehouseClient.DEFAULT_MTLS_ENDPOINT + assert WarehouseClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert WarehouseClient._get_api_endpoint(None, None, default_universe, "always") == WarehouseClient.DEFAULT_MTLS_ENDPOINT + assert WarehouseClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == WarehouseClient.DEFAULT_MTLS_ENDPOINT + assert WarehouseClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert WarehouseClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + WarehouseClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert WarehouseClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert WarehouseClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert WarehouseClient._get_universe_domain(None, None) == WarehouseClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + WarehouseClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc"), + (WarehouseClient, transports.WarehouseRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WarehouseClient, "grpc"), + (WarehouseAsyncClient, "grpc_asyncio"), + (WarehouseClient, "rest"), +]) +def test_warehouse_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WarehouseGrpcTransport, "grpc"), + (transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WarehouseRestTransport, "rest"), +]) +def test_warehouse_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WarehouseClient, "grpc"), + (WarehouseAsyncClient, "grpc_asyncio"), + (WarehouseClient, "rest"), +]) +def test_warehouse_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://visionai.googleapis.com' + ) + + +def test_warehouse_client_get_transport_class(): + transport = WarehouseClient.get_transport_class() + available_transports = [ + transports.WarehouseGrpcTransport, + transports.WarehouseRestTransport, + ] + assert transport in available_transports + + transport = WarehouseClient.get_transport_class("grpc") + assert transport == transports.WarehouseGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio"), + (WarehouseClient, transports.WarehouseRestTransport, "rest"), +]) +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +def test_warehouse_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(WarehouseClient, '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(WarehouseClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", "true"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", "false"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WarehouseClient, transports.WarehouseRestTransport, "rest", "true"), + (WarehouseClient, transports.WarehouseRestTransport, "rest", "false"), +]) +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_warehouse_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + WarehouseClient, WarehouseAsyncClient +]) +@mock.patch.object(WarehouseClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WarehouseAsyncClient)) +def test_warehouse_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + WarehouseClient, WarehouseAsyncClient +]) +@mock.patch.object(WarehouseClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseClient)) +@mock.patch.object(WarehouseAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(WarehouseAsyncClient)) +def test_warehouse_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WarehouseClient._DEFAULT_UNIVERSE + default_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = WarehouseClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc"), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio"), + (WarehouseClient, transports.WarehouseRestTransport, "rest"), +]) +def test_warehouse_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", grpc_helpers), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WarehouseClient, transports.WarehouseRestTransport, "rest", None), +]) +def test_warehouse_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_warehouse_client_client_options_from_dict(): + with mock.patch('google.cloud.visionai_v1alpha1.services.warehouse.transports.WarehouseGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WarehouseClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (WarehouseClient, transports.WarehouseGrpcTransport, "grpc", grpc_helpers), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_warehouse_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "visionai.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAssetRequest, + dict, +]) +def test_create_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset( + name='name_value', + ) + response = client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +def test_create_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAssetRequest() + + +def test_create_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateAssetRequest( + parent='parent_value', + asset_id='asset_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAssetRequest( + parent='parent_value', + asset_id='asset_id_value', + ) + +def test_create_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_asset] = mock_rpc + request = {} + client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.create_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAssetRequest() + +@pytest.mark.asyncio +async def test_create_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_asset] = mock_object + + request = {} + await client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_asset_async_from_dict(): + await test_create_asset_async(request_type=dict) + + +def test_create_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAssetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + call.return_value = warehouse.Asset() + client.create_asset(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_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAssetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + await client.create_asset(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_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_asset( + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].asset_id + mock_val = 'asset_id_value' + assert arg == mock_val + + +def test_create_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.CreateAssetRequest(), + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + +@pytest.mark.asyncio +async def test_create_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_asset( + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].asset_id + mock_val = 'asset_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.CreateAssetRequest(), + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAssetRequest, + dict, +]) +def test_update_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset( + name='name_value', + ) + response = client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +def test_update_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAssetRequest() + + +def test_update_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateAssetRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAssetRequest( + ) + +def test_update_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_asset] = mock_rpc + request = {} + client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.update_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAssetRequest() + +@pytest.mark.asyncio +async def test_update_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_asset] = mock_object + + request = {} + await client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_asset_async_from_dict(): + await test_update_asset_async(request_type=dict) + + +def test_update_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAssetRequest() + + request.asset.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + call.return_value = warehouse.Asset() + client.update_asset(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', + 'asset.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAssetRequest() + + request.asset.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + await client.update_asset(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', + 'asset.name=name_value', + ) in kw['metadata'] + + +def test_update_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_asset( + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.UpdateAssetRequest(), + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_asset( + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].asset + mock_val = warehouse.Asset(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.UpdateAssetRequest(), + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAssetRequest, + dict, +]) +def test_get_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset( + name='name_value', + ) + response = client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +def test_get_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAssetRequest() + + +def test_get_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAssetRequest( + name='name_value', + ) + +def test_get_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_asset] = mock_rpc + request = {} + client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.get_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAssetRequest() + +@pytest.mark.asyncio +async def test_get_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_asset] = mock_object + + request = {} + await client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset( + name='name_value', + )) + response = await client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_asset_async_from_dict(): + await test_get_asset_async(request_type=dict) + + +def test_get_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + call.return_value = warehouse.Asset() + client.get_asset(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_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + await client.get_asset(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_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.GetAssetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Asset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Asset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.GetAssetRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_assets_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 = WarehouseClient( + 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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListAssetsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAssetsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListAssetsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = warehouse.ListAssetsResponse() + client.list_assets(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_assets_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse()) + await client.list_assets(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_assets_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_assets_flattened_error(): + client = WarehouseClient( + 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_assets( + warehouse.ListAssetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_assets_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_assets_flattened_error_async(): + client = WarehouseAsyncClient( + 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_assets( + warehouse.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Asset) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Asset) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAssetRequest, + dict, +]) +def test_delete_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_asset_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 = WarehouseClient( + 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_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAssetRequest() + + +def test_delete_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAssetRequest( + name='name_value', + ) + +def test_delete_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_asset] = mock_rpc + request = {} + client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAssetRequest() + +@pytest.mark.asyncio +async def test_delete_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_asset] = mock_object + + request = {} + await client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_asset_async_from_dict(): + await test_delete_asset_async(request_type=dict) + + +def test_delete_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_asset(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_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_asset(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_asset_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_asset_flattened_error(): + client = WarehouseClient( + 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_asset( + warehouse.DeleteAssetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_asset_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_asset( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_asset_flattened_error_async(): + client = WarehouseAsyncClient( + 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_asset( + warehouse.DeleteAssetRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateCorpusRequest, + dict, +]) +def test_create_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCorpusRequest() + + +def test_create_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateCorpusRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCorpusRequest( + parent='parent_value', + ) + +def test_create_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_corpus] = mock_rpc + request = {} + client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateCorpusRequest() + +@pytest.mark.asyncio +async def test_create_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_corpus] = mock_object + + request = {} + await client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_corpus_async_from_dict(): + await test_create_corpus_async(request_type=dict) + + +def test_create_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateCorpusRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_corpus(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_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateCorpusRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_corpus(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_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_corpus( + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + + +def test_create_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.CreateCorpusRequest(), + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_corpus( + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.CreateCorpusRequest(), + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetCorpusRequest, + dict, +]) +def test_get_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCorpusRequest() + + +def test_get_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetCorpusRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCorpusRequest( + name='name_value', + ) + +def test_get_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_corpus] = mock_rpc + request = {} + client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetCorpusRequest() + +@pytest.mark.asyncio +async def test_get_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_corpus] = mock_object + + request = {} + await client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_corpus_async_from_dict(): + await test_get_corpus_async(request_type=dict) + + +def test_get_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + call.return_value = warehouse.Corpus() + client.get_corpus(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_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + await client.get_corpus(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_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.GetCorpusRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.GetCorpusRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateCorpusRequest, + dict, +]) +def test_update_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCorpusRequest() + + +def test_update_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateCorpusRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCorpusRequest( + ) + +def test_update_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_corpus] = mock_rpc + request = {} + client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateCorpusRequest() + +@pytest.mark.asyncio +async def test_update_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_corpus] = mock_object + + request = {} + await client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_corpus_async_from_dict(): + await test_update_corpus_async(request_type=dict) + + +def test_update_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateCorpusRequest() + + request.corpus.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + call.return_value = warehouse.Corpus() + client.update_corpus(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', + 'corpus.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateCorpusRequest() + + request.corpus.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + await client.update_corpus(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', + 'corpus.name=name_value', + ) in kw['metadata'] + + +def test_update_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_corpus( + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.UpdateCorpusRequest(), + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Corpus() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Corpus()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_corpus( + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].corpus + mock_val = warehouse.Corpus(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.UpdateCorpusRequest(), + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListCorporaRequest, + dict, +]) +def test_list_corpora(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + ) + response = client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListCorporaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCorporaPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_corpora_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 = WarehouseClient( + 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_corpora), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_corpora() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCorporaRequest() + + +def test_list_corpora_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListCorporaRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_corpora(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCorporaRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_corpora_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_corpora in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_corpora] = mock_rpc + request = {} + client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_corpora(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_corpora_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_corpora() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListCorporaRequest() + +@pytest.mark.asyncio +async def test_list_corpora_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_corpora in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_corpora] = mock_object + + request = {} + await client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_corpora(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_corpora_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListCorporaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListCorporaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCorporaAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_corpora_async_from_dict(): + await test_list_corpora_async(request_type=dict) + + +def test_list_corpora_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListCorporaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + call.return_value = warehouse.ListCorporaResponse() + client.list_corpora(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_corpora_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListCorporaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse()) + await client.list_corpora(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_corpora_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCorporaResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_corpora( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_corpora_flattened_error(): + client = WarehouseClient( + 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_corpora( + warehouse.ListCorporaRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_corpora_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListCorporaResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListCorporaResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_corpora( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_corpora_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpora( + warehouse.ListCorporaRequest(), + parent='parent_value', + ) + + +def test_list_corpora_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_corpora(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Corpus) + for i in results) +def test_list_corpora_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + pages = list(client.list_corpora(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_corpora_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_corpora(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Corpus) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_corpora_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_corpora), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_corpora(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteCorpusRequest, + dict, +]) +def test_delete_corpus(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_corpus_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 = WarehouseClient( + 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_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCorpusRequest() + + +def test_delete_corpus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteCorpusRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_corpus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCorpusRequest( + name='name_value', + ) + +def test_delete_corpus_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_corpus] = mock_rpc + request = {} + client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_corpus_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_corpus() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteCorpusRequest() + +@pytest.mark.asyncio +async def test_delete_corpus_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_corpus in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_corpus] = mock_object + + request = {} + await client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_corpus_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteCorpusRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_corpus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteCorpusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_corpus_async_from_dict(): + await test_delete_corpus_async(request_type=dict) + + +def test_delete_corpus_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + call.return_value = None + client.delete_corpus(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_corpus_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteCorpusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_corpus(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_corpus_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__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_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_corpus_flattened_error(): + client = WarehouseClient( + 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_corpus( + warehouse.DeleteCorpusRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_corpus_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_corpus), + '__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_corpus( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_corpus_flattened_error_async(): + client = WarehouseAsyncClient( + 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_corpus( + warehouse.DeleteCorpusRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateDataSchemaRequest, + dict, +]) +def test_create_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + response = client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +def test_create_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateDataSchemaRequest() + + +def test_create_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateDataSchemaRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateDataSchemaRequest( + parent='parent_value', + ) + +def test_create_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_schema] = mock_rpc + request = {} + client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.create_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateDataSchemaRequest() + +@pytest.mark.asyncio +async def test_create_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_data_schema] = mock_object + + request = {} + await client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +@pytest.mark.asyncio +async def test_create_data_schema_async_from_dict(): + await test_create_data_schema_async(request_type=dict) + + +def test_create_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateDataSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + call.return_value = warehouse.DataSchema() + client.create_data_schema(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_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateDataSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + await client.create_data_schema(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_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_data_schema( + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + + +def test_create_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.CreateDataSchemaRequest(), + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_data_schema( + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.CreateDataSchemaRequest(), + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateDataSchemaRequest, + dict, +]) +def test_update_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + response = client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +def test_update_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateDataSchemaRequest() + + +def test_update_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateDataSchemaRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateDataSchemaRequest( + ) + +def test_update_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_schema] = mock_rpc + request = {} + client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.update_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateDataSchemaRequest() + +@pytest.mark.asyncio +async def test_update_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_data_schema] = mock_object + + request = {} + await client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +@pytest.mark.asyncio +async def test_update_data_schema_async_from_dict(): + await test_update_data_schema_async(request_type=dict) + + +def test_update_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateDataSchemaRequest() + + request.data_schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + call.return_value = warehouse.DataSchema() + client.update_data_schema(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', + 'data_schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateDataSchemaRequest() + + request.data_schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + await client.update_data_schema(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', + 'data_schema.name=name_value', + ) in kw['metadata'] + + +def test_update_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_schema( + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.UpdateDataSchemaRequest(), + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_schema( + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_schema + mock_val = warehouse.DataSchema(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.UpdateDataSchemaRequest(), + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetDataSchemaRequest, + dict, +]) +def test_get_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + response = client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +def test_get_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetDataSchemaRequest() + + +def test_get_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetDataSchemaRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetDataSchemaRequest( + name='name_value', + ) + +def test_get_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_schema] = mock_rpc + request = {} + client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.get_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetDataSchemaRequest() + +@pytest.mark.asyncio +async def test_get_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_schema] = mock_object + + request = {} + await client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema( + name='name_value', + key='key_value', + )) + response = await client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + + +@pytest.mark.asyncio +async def test_get_data_schema_async_from_dict(): + await test_get_data_schema_async(request_type=dict) + + +def test_get_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + call.return_value = warehouse.DataSchema() + client.get_data_schema(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_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + await client.get_data_schema(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_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.GetDataSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.DataSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.DataSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.GetDataSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteDataSchemaRequest, + dict, +]) +def test_delete_data_schema(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_data_schema_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 = WarehouseClient( + 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_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteDataSchemaRequest() + + +def test_delete_data_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteDataSchemaRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteDataSchemaRequest( + name='name_value', + ) + +def test_delete_data_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_schema] = mock_rpc + request = {} + client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteDataSchemaRequest() + +@pytest.mark.asyncio +async def test_delete_data_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_data_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_data_schema] = mock_object + + request = {} + await client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_schema_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteDataSchemaRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteDataSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_data_schema_async_from_dict(): + await test_delete_data_schema_async(request_type=dict) + + +def test_delete_data_schema_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + call.return_value = None + client.delete_data_schema(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_data_schema_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteDataSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_data_schema(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_data_schema_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__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_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_data_schema_flattened_error(): + client = WarehouseClient( + 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_data_schema( + warehouse.DeleteDataSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_data_schema_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_schema), + '__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_data_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_data_schema_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schema( + warehouse.DeleteDataSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListDataSchemasRequest, + dict, +]) +def test_list_data_schemas(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListDataSchemasRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_schemas_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 = WarehouseClient( + 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_data_schemas), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListDataSchemasRequest() + + +def test_list_data_schemas_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListDataSchemasRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_schemas(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListDataSchemasRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_data_schemas_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_schemas in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_schemas] = mock_rpc + request = {} + client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_schemas_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListDataSchemasRequest() + +@pytest.mark.asyncio +async def test_list_data_schemas_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_data_schemas in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_data_schemas] = mock_object + + request = {} + await client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_data_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_schemas_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListDataSchemasRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListDataSchemasRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSchemasAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_schemas_async_from_dict(): + await test_list_data_schemas_async(request_type=dict) + + +def test_list_data_schemas_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListDataSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + call.return_value = warehouse.ListDataSchemasResponse() + client.list_data_schemas(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_data_schemas_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListDataSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse()) + await client.list_data_schemas(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_data_schemas_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListDataSchemasResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_data_schemas_flattened_error(): + client = WarehouseClient( + 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_data_schemas( + warehouse.ListDataSchemasRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_data_schemas_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListDataSchemasResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListDataSchemasResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_data_schemas_flattened_error_async(): + client = WarehouseAsyncClient( + 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_data_schemas( + warehouse.ListDataSchemasRequest(), + parent='parent_value', + ) + + +def test_list_data_schemas_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_schemas(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.DataSchema) + for i in results) +def test_list_data_schemas_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_schemas(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_data_schemas_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_schemas(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.DataSchema) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_schemas_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_data_schemas(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAnnotationRequest, + dict, +]) +def test_create_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation( + name='name_value', + ) + response = client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +def test_create_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAnnotationRequest() + + +def test_create_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateAnnotationRequest( + parent='parent_value', + annotation_id='annotation_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAnnotationRequest( + parent='parent_value', + annotation_id='annotation_id_value', + ) + +def test_create_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_annotation] = mock_rpc + request = {} + client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.create_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateAnnotationRequest() + +@pytest.mark.asyncio +async def test_create_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_annotation] = mock_object + + request = {} + await client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_annotation_async_from_dict(): + await test_create_annotation_async(request_type=dict) + + +def test_create_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAnnotationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + call.return_value = warehouse.Annotation() + client.create_annotation(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_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateAnnotationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + await client.create_annotation(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_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_annotation( + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].annotation_id + mock_val = 'annotation_id_value' + assert arg == mock_val + + +def test_create_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.CreateAnnotationRequest(), + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_annotation( + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].annotation_id + mock_val = 'annotation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.CreateAnnotationRequest(), + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAnnotationRequest, + dict, +]) +def test_get_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation( + name='name_value', + ) + response = client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +def test_get_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAnnotationRequest() + + +def test_get_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetAnnotationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAnnotationRequest( + name='name_value', + ) + +def test_get_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_annotation] = mock_rpc + request = {} + client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.get_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetAnnotationRequest() + +@pytest.mark.asyncio +async def test_get_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_annotation] = mock_object + + request = {} + await client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_annotation_async_from_dict(): + await test_get_annotation_async(request_type=dict) + + +def test_get_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + call.return_value = warehouse.Annotation() + client.get_annotation(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_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + await client.get_annotation(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_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.GetAnnotationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.GetAnnotationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAnnotationsRequest, + dict, +]) +def test_list_annotations(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListAnnotationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_annotations_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 = WarehouseClient( + 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_annotations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_annotations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAnnotationsRequest() + + +def test_list_annotations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListAnnotationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_annotations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAnnotationsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_annotations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_annotations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_annotations] = mock_rpc + request = {} + client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_annotations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_annotations_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_annotations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListAnnotationsRequest() + +@pytest.mark.asyncio +async def test_list_annotations_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_annotations in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_annotations] = mock_object + + request = {} + await client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_annotations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_annotations_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListAnnotationsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListAnnotationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_annotations_async_from_dict(): + await test_list_annotations_async(request_type=dict) + + +def test_list_annotations_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAnnotationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + call.return_value = warehouse.ListAnnotationsResponse() + client.list_annotations(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_annotations_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListAnnotationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse()) + await client.list_annotations(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_annotations_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAnnotationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_annotations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_annotations_flattened_error(): + client = WarehouseClient( + 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_annotations( + warehouse.ListAnnotationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_annotations_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListAnnotationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListAnnotationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_annotations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_annotations_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotations( + warehouse.ListAnnotationsRequest(), + parent='parent_value', + ) + + +def test_list_annotations_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_annotations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Annotation) + for i in results) +def test_list_annotations_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_annotations(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_annotations_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_annotations(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.Annotation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_annotations_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_annotations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_annotations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAnnotationRequest, + dict, +]) +def test_update_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation( + name='name_value', + ) + response = client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +def test_update_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAnnotationRequest() + + +def test_update_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateAnnotationRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAnnotationRequest( + ) + +def test_update_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_annotation] = mock_rpc + request = {} + client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.update_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateAnnotationRequest() + +@pytest.mark.asyncio +async def test_update_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_annotation] = mock_object + + request = {} + await client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation( + name='name_value', + )) + response = await client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_annotation_async_from_dict(): + await test_update_annotation_async(request_type=dict) + + +def test_update_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAnnotationRequest() + + request.annotation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + call.return_value = warehouse.Annotation() + client.update_annotation(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', + 'annotation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateAnnotationRequest() + + request.annotation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + await client.update_annotation(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', + 'annotation.name=name_value', + ) in kw['metadata'] + + +def test_update_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_annotation( + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.UpdateAnnotationRequest(), + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.Annotation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.Annotation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_annotation( + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].annotation + mock_val = warehouse.Annotation(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.UpdateAnnotationRequest(), + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAnnotationRequest, + dict, +]) +def test_delete_annotation(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_annotation_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 = WarehouseClient( + 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_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAnnotationRequest() + + +def test_delete_annotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteAnnotationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_annotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAnnotationRequest( + name='name_value', + ) + +def test_delete_annotation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_annotation] = mock_rpc + request = {} + client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_annotation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_annotation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteAnnotationRequest() + +@pytest.mark.asyncio +async def test_delete_annotation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_annotation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_annotation] = mock_object + + request = {} + await client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_annotation_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteAnnotationRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_annotation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteAnnotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_annotation_async_from_dict(): + await test_delete_annotation_async(request_type=dict) + + +def test_delete_annotation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + call.return_value = None + client.delete_annotation(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_annotation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteAnnotationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_annotation(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_annotation_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__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_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_annotation_flattened_error(): + client = WarehouseClient( + 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_annotation( + warehouse.DeleteAnnotationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_annotation_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_annotation), + '__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_annotation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_annotation_flattened_error_async(): + client = WarehouseAsyncClient( + 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_annotation( + warehouse.DeleteAnnotationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.IngestAssetRequest, + dict, +]) +def test_ingest_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.ingest_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([warehouse.IngestAssetResponse()]) + response = client.ingest_asset(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, warehouse.IngestAssetResponse) + + +def test_ingest_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.ingest_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.ingest_asset] = mock_rpc + request = [{}] + client.ingest_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.ingest_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_ingest_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.ingest_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.ingest_asset] = mock_object + + request = [{}] + await client.ingest_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.ingest_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_ingest_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.IngestAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.ingest_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[warehouse.IngestAssetResponse()]) + response = await client.ingest_asset(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, warehouse.IngestAssetResponse) + + +@pytest.mark.asyncio +async def test_ingest_asset_async_from_dict(): + await test_ingest_asset_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ClipAssetRequest, + dict, +]) +def test_clip_asset(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ClipAssetResponse( + ) + response = client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ClipAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.ClipAssetResponse) + + +def test_clip_asset_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 = WarehouseClient( + 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.clip_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.clip_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ClipAssetRequest() + + +def test_clip_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ClipAssetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.clip_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ClipAssetRequest( + name='name_value', + ) + +def test_clip_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clip_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clip_asset] = mock_rpc + request = {} + client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.clip_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_clip_asset_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ClipAssetResponse( + )) + response = await client.clip_asset() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ClipAssetRequest() + +@pytest.mark.asyncio +async def test_clip_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.clip_asset in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.clip_asset] = mock_object + + request = {} + await client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.clip_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_clip_asset_async(transport: str = 'grpc_asyncio', request_type=warehouse.ClipAssetRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ClipAssetResponse( + )) + response = await client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ClipAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.ClipAssetResponse) + + +@pytest.mark.asyncio +async def test_clip_asset_async_from_dict(): + await test_clip_asset_async(request_type=dict) + + +def test_clip_asset_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ClipAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + call.return_value = warehouse.ClipAssetResponse() + client.clip_asset(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_clip_asset_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ClipAssetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clip_asset), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ClipAssetResponse()) + await client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.GenerateHlsUriRequest, + dict, +]) +def test_generate_hls_uri(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.GenerateHlsUriResponse( + uri='uri_value', + ) + response = client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GenerateHlsUriRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateHlsUriResponse) + assert response.uri == 'uri_value' + + +def test_generate_hls_uri_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 = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_hls_uri() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateHlsUriRequest() + + +def test_generate_hls_uri_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GenerateHlsUriRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_hls_uri(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateHlsUriRequest( + name='name_value', + ) + +def test_generate_hls_uri_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_hls_uri in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_hls_uri] = mock_rpc + request = {} + client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_hls_uri(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_hls_uri_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateHlsUriResponse( + uri='uri_value', + )) + response = await client.generate_hls_uri() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GenerateHlsUriRequest() + +@pytest.mark.asyncio +async def test_generate_hls_uri_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_hls_uri in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.generate_hls_uri] = mock_object + + request = {} + await client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.generate_hls_uri(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_hls_uri_async(transport: str = 'grpc_asyncio', request_type=warehouse.GenerateHlsUriRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateHlsUriResponse( + uri='uri_value', + )) + response = await client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GenerateHlsUriRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateHlsUriResponse) + assert response.uri == 'uri_value' + + +@pytest.mark.asyncio +async def test_generate_hls_uri_async_from_dict(): + await test_generate_hls_uri_async(request_type=dict) + + +def test_generate_hls_uri_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GenerateHlsUriRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value = warehouse.GenerateHlsUriResponse() + client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_hls_uri_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GenerateHlsUriRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_hls_uri), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.GenerateHlsUriResponse()) + await client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateSearchConfigRequest, + dict, +]) +def test_create_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig( + name='name_value', + ) + response = client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.CreateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +def test_create_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchConfigRequest() + + +def test_create_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.CreateSearchConfigRequest( + parent='parent_value', + search_config_id='search_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchConfigRequest( + parent='parent_value', + search_config_id='search_config_id_value', + ) + +def test_create_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_config] = mock_rpc + request = {} + client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.create_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.CreateSearchConfigRequest() + +@pytest.mark.asyncio +async def test_create_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.create_search_config] = mock_object + + request = {} + await client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.CreateSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.CreateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_search_config_async_from_dict(): + await test_create_search_config_async(request_type=dict) + + +def test_create_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateSearchConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + call.return_value = warehouse.SearchConfig() + client.create_search_config(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_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.CreateSearchConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + await client.create_search_config(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_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_search_config( + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].search_config_id + mock_val = 'search_config_id_value' + assert arg == mock_val + + +def test_create_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.CreateSearchConfigRequest(), + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_search_config( + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].search_config_id + mock_val = 'search_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.CreateSearchConfigRequest(), + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateSearchConfigRequest, + dict, +]) +def test_update_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig( + name='name_value', + ) + response = client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +def test_update_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchConfigRequest() + + +def test_update_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.UpdateSearchConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchConfigRequest( + ) + +def test_update_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_config] = mock_rpc + request = {} + client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.update_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.UpdateSearchConfigRequest() + +@pytest.mark.asyncio +async def test_update_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.update_search_config] = mock_object + + request = {} + await client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.UpdateSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.UpdateSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_search_config_async_from_dict(): + await test_update_search_config_async(request_type=dict) + + +def test_update_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateSearchConfigRequest() + + request.search_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + call.return_value = warehouse.SearchConfig() + client.update_search_config(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', + 'search_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.UpdateSearchConfigRequest() + + request.search_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + await client.update_search_config(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', + 'search_config.name=name_value', + ) in kw['metadata'] + + +def test_update_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_search_config( + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.UpdateSearchConfigRequest(), + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_search_config( + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].search_config + mock_val = warehouse.SearchConfig(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.UpdateSearchConfigRequest(), + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetSearchConfigRequest, + dict, +]) +def test_get_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig( + name='name_value', + ) + response = client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.GetSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +def test_get_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchConfigRequest() + + +def test_get_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.GetSearchConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchConfigRequest( + name='name_value', + ) + +def test_get_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_config] = mock_rpc + request = {} + client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.get_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.GetSearchConfigRequest() + +@pytest.mark.asyncio +async def test_get_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.get_search_config] = mock_object + + request = {} + await client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.GetSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig( + name='name_value', + )) + response = await client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.GetSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_search_config_async_from_dict(): + await test_get_search_config_async(request_type=dict) + + +def test_get_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + call.return_value = warehouse.SearchConfig() + client.get_search_config(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_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.GetSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + await client.get_search_config(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_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.GetSearchConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.GetSearchConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteSearchConfigRequest, + dict, +]) +def test_delete_search_config(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_search_config_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 = WarehouseClient( + 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_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchConfigRequest() + + +def test_delete_search_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.DeleteSearchConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchConfigRequest( + name='name_value', + ) + +def test_delete_search_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_config] = mock_rpc + request = {} + client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.DeleteSearchConfigRequest() + +@pytest.mark.asyncio +async def test_delete_search_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_search_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.delete_search_config] = mock_object + + request = {} + await client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_config_async(transport: str = 'grpc_asyncio', request_type=warehouse.DeleteSearchConfigRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.DeleteSearchConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_search_config_async_from_dict(): + await test_delete_search_config_async(request_type=dict) + + +def test_delete_search_config_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + call.return_value = None + client.delete_search_config(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_search_config_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.DeleteSearchConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_search_config(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_search_config_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__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_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_search_config_flattened_error(): + client = WarehouseClient( + 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_search_config( + warehouse.DeleteSearchConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_search_config_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_config), + '__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_search_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_search_config_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_config( + warehouse.DeleteSearchConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListSearchConfigsRequest, + dict, +]) +def test_list_search_configs(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.ListSearchConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_search_configs_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 = WarehouseClient( + 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_search_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchConfigsRequest() + + +def test_list_search_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.ListSearchConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_search_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_configs] = mock_rpc + request = {} + client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.ListSearchConfigsRequest() + +@pytest.mark.asyncio +async def test_list_search_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_search_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.list_search_configs] = mock_object + + request = {} + await client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_search_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_configs_async(transport: str = 'grpc_asyncio', request_type=warehouse.ListSearchConfigsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.ListSearchConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_search_configs_async_from_dict(): + await test_list_search_configs_async(request_type=dict) + + +def test_list_search_configs_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListSearchConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + call.return_value = warehouse.ListSearchConfigsResponse() + client.list_search_configs(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_search_configs_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.ListSearchConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse()) + await client.list_search_configs(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_search_configs_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_search_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_search_configs_flattened_error(): + client = WarehouseClient( + 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_search_configs( + warehouse.ListSearchConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_search_configs_flattened_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.ListSearchConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.ListSearchConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_search_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_search_configs_flattened_error_async(): + client = WarehouseAsyncClient( + 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_search_configs( + warehouse.ListSearchConfigsRequest(), + parent='parent_value', + ) + + +def test_list_search_configs_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_search_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchConfig) + for i in results) +def test_list_search_configs_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_search_configs(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_search_configs_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_search_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.SearchConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_search_configs_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_search_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + warehouse.SearchAssetsRequest, + dict, +]) +def test_search_assets(request_type, transport: str = 'grpc'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = warehouse.SearchAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_assets_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 = WarehouseClient( + 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.search_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchAssetsRequest() + + +def test_search_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = warehouse.SearchAssetsRequest( + corpus='corpus_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchAssetsRequest( + corpus='corpus_value', + page_token='page_token_value', + ) + +def test_search_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_assets] = mock_rpc + request = {} + client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == warehouse.SearchAssetsRequest() + +@pytest.mark.asyncio +async def test_search_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.search_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[client._client._transport.search_assets] = mock_object + + request = {} + await client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.search_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_search_assets_async(transport: str = 'grpc_asyncio', request_type=warehouse.SearchAssetsRequest): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = warehouse.SearchAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_assets_async_from_dict(): + await test_search_assets_async(request_type=dict) + + +def test_search_assets_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.SearchAssetsRequest() + + request.corpus = 'corpus_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + call.return_value = warehouse.SearchAssetsResponse() + client.search_assets(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', + 'corpus=corpus_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_assets_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = warehouse.SearchAssetsRequest() + + request.corpus = 'corpus_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(warehouse.SearchAssetsResponse()) + await client.search_assets(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', + 'corpus=corpus_value', + ) in kw['metadata'] + + +def test_search_assets_pager(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('corpus', ''), + )), + ) + pager = client.search_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in results) +def test_search_assets_pages(transport_name: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + pages = list(client.search_assets(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_search_assets_async_pager(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_assets(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_assets_async_pages(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAssetRequest, + dict, +]) +def test_create_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["asset"] = {'name': 'name_value', 'ttl': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateAssetRequest.meta.fields["asset"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["asset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["asset"][field])): + del request_init["asset"][field][i][subfield] + else: + del request_init["asset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + +def test_create_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_asset] = mock_rpc + + request = {} + client.create_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_asset_rest_required_fields(request_type=warehouse.CreateAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_asset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetId", )) & set(("parent", "asset", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateAssetRequest.pb(warehouse.CreateAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Asset.to_json(warehouse.Asset()) + + request = warehouse.CreateAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Asset() + + client.create_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_asset(request) + + +def test_create_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*}/assets" % client.transport._host, args[1]) + + +def test_create_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_asset( + warehouse.CreateAssetRequest(), + parent='parent_value', + asset=warehouse.Asset(name='name_value'), + asset_id='asset_id_value', + ) + + +def test_create_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAssetRequest, + dict, +]) +def test_update_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'asset': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'}} + request_init["asset"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4', 'ttl': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateAssetRequest.meta.fields["asset"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["asset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["asset"][field])): + del request_init["asset"][field][i][subfield] + else: + del request_init["asset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + +def test_update_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_asset] = mock_rpc + + request = {} + client.update_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_asset_rest_required_fields(request_type=warehouse.UpdateAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_asset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("asset", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateAssetRequest.pb(warehouse.UpdateAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Asset.to_json(warehouse.Asset()) + + request = warehouse.UpdateAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Asset() + + client.update_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'asset': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_asset(request) + + +def test_update_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + + # get arguments that satisfy an http rule for this method + sample_request = {'asset': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{asset.name=projects/*/locations/*/corpora/*/assets/*}" % client.transport._host, args[1]) + + +def test_update_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_asset( + warehouse.UpdateAssetRequest(), + asset=warehouse.Asset(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAssetRequest, + dict, +]) +def test_get_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Asset) + assert response.name == 'name_value' + +def test_get_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_asset] = mock_rpc + + request = {} + client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_asset_rest_required_fields(request_type=warehouse.GetAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetAssetRequest.pb(warehouse.GetAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Asset.to_json(warehouse.Asset()) + + request = warehouse.GetAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Asset() + + client.get_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_asset(request) + + +def test_get_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Asset() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*}" % client.transport._host, args[1]) + + +def test_get_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_asset( + warehouse.GetAssetRequest(), + name='name_value', + ) + + +def test_get_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_assets_rest_required_fields(request_type=warehouse.ListAssetsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListAssetsRequest.pb(warehouse.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListAssetsResponse.to_json(warehouse.ListAssetsResponse()) + + request = warehouse.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListAssetsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_assets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*}/assets" % client.transport._host, args[1]) + + +def test_list_assets_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_assets( + warehouse.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + warehouse.Asset(), + ], + next_page_token='abc', + ), + warehouse.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + ], + next_page_token='ghi', + ), + warehouse.ListAssetsResponse( + assets=[ + warehouse.Asset(), + warehouse.Asset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListAssetsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Asset) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAssetRequest, + dict, +]) +def test_delete_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_asset(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_delete_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_asset] = mock_rpc + + request = {} + client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_asset_rest_required_fields(request_type=warehouse.DeleteAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_delete_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.DeleteAssetRequest.pb(warehouse.DeleteAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.DeleteAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_asset(request) + + +def test_delete_asset_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_asset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*}" % client.transport._host, args[1]) + + +def test_delete_asset_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_asset( + warehouse.DeleteAssetRequest(), + name='name_value', + ) + + +def test_delete_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateCorpusRequest, + dict, +]) +def test_create_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["corpus"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'default_ttl': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateCorpusRequest.meta.fields["corpus"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["corpus"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["corpus"][field])): + del request_init["corpus"][field][i][subfield] + else: + del request_init["corpus"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_corpus(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_create_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_corpus] = mock_rpc + + request = {} + client.create_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_corpus_rest_required_fields(request_type=warehouse.CreateCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "corpus", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_corpus") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_corpus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateCorpusRequest.pb(warehouse.CreateCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = warehouse.CreateCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_corpus(request) + + +def test_create_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/corpora" % client.transport._host, args[1]) + + +def test_create_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_corpus( + warehouse.CreateCorpusRequest(), + parent='parent_value', + corpus=warehouse.Corpus(name='name_value'), + ) + + +def test_create_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetCorpusRequest, + dict, +]) +def test_get_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_corpus(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_corpus] = mock_rpc + + request = {} + client.get_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_corpus_rest_required_fields(request_type=warehouse.GetCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_corpus") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_corpus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetCorpusRequest.pb(warehouse.GetCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Corpus.to_json(warehouse.Corpus()) + + request = warehouse.GetCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Corpus() + + client.get_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_corpus(request) + + +def test_get_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*}" % client.transport._host, args[1]) + + +def test_get_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_corpus( + warehouse.GetCorpusRequest(), + name='name_value', + ) + + +def test_get_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateCorpusRequest, + dict, +]) +def test_update_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': {'name': 'projects/sample1/locations/sample2/corpora/sample3'}} + request_init["corpus"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'default_ttl': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateCorpusRequest.meta.fields["corpus"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["corpus"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["corpus"][field])): + del request_init["corpus"][field][i][subfield] + else: + del request_init["corpus"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_corpus(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Corpus) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_update_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_corpus] = mock_rpc + + request = {} + client.update_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_corpus_rest_required_fields(request_type=warehouse.UpdateCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_corpus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("corpus", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_corpus") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_corpus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateCorpusRequest.pb(warehouse.UpdateCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Corpus.to_json(warehouse.Corpus()) + + request = warehouse.UpdateCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Corpus() + + client.update_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': {'name': 'projects/sample1/locations/sample2/corpora/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_corpus(request) + + +def test_update_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Corpus() + + # get arguments that satisfy an http rule for this method + sample_request = {'corpus': {'name': 'projects/sample1/locations/sample2/corpora/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Corpus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{corpus.name=projects/*/locations/*/corpora/*}" % client.transport._host, args[1]) + + +def test_update_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_corpus( + warehouse.UpdateCorpusRequest(), + corpus=warehouse.Corpus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListCorporaRequest, + dict, +]) +def test_list_corpora_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCorporaResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListCorporaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_corpora(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCorporaPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_corpora_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_corpora in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_corpora] = mock_rpc + + request = {} + client.list_corpora(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_corpora(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_corpora_rest_required_fields(request_type=warehouse.ListCorporaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_corpora._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_corpora._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCorporaResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListCorporaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_corpora(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_corpora_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_corpora._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_corpora_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_corpora") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_corpora") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListCorporaRequest.pb(warehouse.ListCorporaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListCorporaResponse.to_json(warehouse.ListCorporaResponse()) + + request = warehouse.ListCorporaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListCorporaResponse() + + client.list_corpora(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_corpora_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListCorporaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_corpora(request) + + +def test_list_corpora_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListCorporaResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListCorporaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_corpora(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/corpora" % client.transport._host, args[1]) + + +def test_list_corpora_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_corpora( + warehouse.ListCorporaRequest(), + parent='parent_value', + ) + + +def test_list_corpora_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + warehouse.Corpus(), + ], + next_page_token='abc', + ), + warehouse.ListCorporaResponse( + corpora=[], + next_page_token='def', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + ], + next_page_token='ghi', + ), + warehouse.ListCorporaResponse( + corpora=[ + warehouse.Corpus(), + warehouse.Corpus(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListCorporaResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_corpora(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Corpus) + for i in results) + + pages = list(client.list_corpora(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteCorpusRequest, + dict, +]) +def test_delete_corpus_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_corpus(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_corpus_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_corpus in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_corpus] = mock_rpc + + request = {} + client.delete_corpus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_corpus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_corpus_rest_required_fields(request_type=warehouse.DeleteCorpusRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_corpus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_corpus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_corpus_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_corpus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_corpus_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_corpus") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteCorpusRequest.pb(warehouse.DeleteCorpusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteCorpusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_corpus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_corpus_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteCorpusRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_corpus(request) + + +def test_delete_corpus_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_corpus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*}" % client.transport._host, args[1]) + + +def test_delete_corpus_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_corpus( + warehouse.DeleteCorpusRequest(), + name='name_value', + ) + + +def test_delete_corpus_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateDataSchemaRequest, + dict, +]) +def test_create_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["data_schema"] = {'name': 'name_value', 'key': 'key_value', 'schema_details': {'type_': 1, 'proto_any_config': {'type_uri': 'type_uri_value'}, 'granularity': 1, 'search_strategy': {'search_strategy_type': 1}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateDataSchemaRequest.meta.fields["data_schema"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_schema"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_schema"][field])): + del request_init["data_schema"][field][i][subfield] + else: + del request_init["data_schema"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_data_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + +def test_create_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_schema] = mock_rpc + + request = {} + client.create_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_data_schema_rest_required_fields(request_type=warehouse.CreateDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "dataSchema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_data_schema") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_data_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateDataSchemaRequest.pb(warehouse.CreateDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.DataSchema.to_json(warehouse.DataSchema()) + + request = warehouse.CreateDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.DataSchema() + + client.create_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_data_schema(request) + + +def test_create_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*}/dataSchemas" % client.transport._host, args[1]) + + +def test_create_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_data_schema( + warehouse.CreateDataSchemaRequest(), + parent='parent_value', + data_schema=warehouse.DataSchema(name='name_value'), + ) + + +def test_create_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateDataSchemaRequest, + dict, +]) +def test_update_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_schema': {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'}} + request_init["data_schema"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4', 'key': 'key_value', 'schema_details': {'type_': 1, 'proto_any_config': {'type_uri': 'type_uri_value'}, 'granularity': 1, 'search_strategy': {'search_strategy_type': 1}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateDataSchemaRequest.meta.fields["data_schema"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_schema"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_schema"][field])): + del request_init["data_schema"][field][i][subfield] + else: + del request_init["data_schema"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + +def test_update_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_schema] = mock_rpc + + request = {} + client.update_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_schema_rest_required_fields(request_type=warehouse.UpdateDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataSchema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_data_schema") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_data_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateDataSchemaRequest.pb(warehouse.UpdateDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.DataSchema.to_json(warehouse.DataSchema()) + + request = warehouse.UpdateDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.DataSchema() + + client.update_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_schema': {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_data_schema(request) + + +def test_update_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_schema': {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{data_schema.name=projects/*/locations/*/corpora/*/dataSchemas/*}" % client.transport._host, args[1]) + + +def test_update_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_schema( + warehouse.UpdateDataSchemaRequest(), + data_schema=warehouse.DataSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetDataSchemaRequest, + dict, +]) +def test_get_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema( + name='name_value', + key='key_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.DataSchema) + assert response.name == 'name_value' + assert response.key == 'key_value' + +def test_get_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_schema] = mock_rpc + + request = {} + client.get_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_schema_rest_required_fields(request_type=warehouse.GetDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_data_schema") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_data_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetDataSchemaRequest.pb(warehouse.GetDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.DataSchema.to_json(warehouse.DataSchema()) + + request = warehouse.GetDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.DataSchema() + + client.get_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_schema(request) + + +def test_get_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.DataSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.DataSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}" % client.transport._host, args[1]) + + +def test_get_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_schema( + warehouse.GetDataSchemaRequest(), + name='name_value', + ) + + +def test_get_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteDataSchemaRequest, + dict, +]) +def test_delete_data_schema_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_data_schema(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_data_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_schema] = mock_rpc + + request = {} + client.delete_data_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_data_schema_rest_required_fields(request_type=warehouse.DeleteDataSchemaRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_data_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_data_schema_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_data_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_schema_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_data_schema") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteDataSchemaRequest.pb(warehouse.DeleteDataSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteDataSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_data_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_data_schema_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteDataSchemaRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_data_schema(request) + + +def test_delete_data_schema_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/dataSchemas/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_data_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/dataSchemas/*}" % client.transport._host, args[1]) + + +def test_delete_data_schema_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_data_schema( + warehouse.DeleteDataSchemaRequest(), + name='name_value', + ) + + +def test_delete_data_schema_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListDataSchemasRequest, + dict, +]) +def test_list_data_schemas_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListDataSchemasResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListDataSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_data_schemas(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSchemasPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_data_schemas_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_schemas in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_schemas] = mock_rpc + + request = {} + client.list_data_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_schemas_rest_required_fields(request_type=warehouse.ListDataSchemasRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_schemas._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_schemas._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListDataSchemasResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListDataSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_data_schemas(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_data_schemas_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_data_schemas._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_schemas_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_data_schemas") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_data_schemas") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListDataSchemasRequest.pb(warehouse.ListDataSchemasRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListDataSchemasResponse.to_json(warehouse.ListDataSchemasResponse()) + + request = warehouse.ListDataSchemasRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListDataSchemasResponse() + + client.list_data_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_data_schemas_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListDataSchemasRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_data_schemas(request) + + +def test_list_data_schemas_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListDataSchemasResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListDataSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_data_schemas(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*}/dataSchemas" % client.transport._host, args[1]) + + +def test_list_data_schemas_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_schemas( + warehouse.ListDataSchemasRequest(), + parent='parent_value', + ) + + +def test_list_data_schemas_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + next_page_token='abc', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[], + next_page_token='def', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + ], + next_page_token='ghi', + ), + warehouse.ListDataSchemasResponse( + data_schemas=[ + warehouse.DataSchema(), + warehouse.DataSchema(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListDataSchemasResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_data_schemas(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.DataSchema) + for i in results) + + pages = list(client.list_data_schemas(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateAnnotationRequest, + dict, +]) +def test_create_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request_init["annotation"] = {'name': 'name_value', 'user_specified_annotation': {'key': 'key_value', 'value': {'int_value': 967, 'float_value': 0.117, 'str_value': 'str_value_value', 'datetime_value': 'datetime_value_value', 'geo_coordinate': {'latitude': 0.86, 'longitude': 0.971}, 'proto_any_value': {'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}, 'bool_value': True, 'customized_struct_data_value': {'fields': {}}}, 'partition': {'temporal_partition': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'spatial_partition': {'x_min': 539, 'y_min': 540, 'x_max': 541, 'y_max': 542}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateAnnotationRequest.meta.fields["annotation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["annotation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["annotation"][field])): + del request_init["annotation"][field][i][subfield] + else: + del request_init["annotation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_annotation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + +def test_create_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_annotation] = mock_rpc + + request = {} + client.create_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_annotation_rest_required_fields(request_type=warehouse.CreateAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_annotation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("annotation_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("annotationId", )) & set(("parent", "annotation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_annotation") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_annotation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateAnnotationRequest.pb(warehouse.CreateAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Annotation.to_json(warehouse.Annotation()) + + request = warehouse.CreateAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Annotation() + + client.create_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_annotation(request) + + +def test_create_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations" % client.transport._host, args[1]) + + +def test_create_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_annotation( + warehouse.CreateAnnotationRequest(), + parent='parent_value', + annotation=warehouse.Annotation(name='name_value'), + annotation_id='annotation_id_value', + ) + + +def test_create_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetAnnotationRequest, + dict, +]) +def test_get_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_annotation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + +def test_get_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_annotation] = mock_rpc + + request = {} + client.get_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_annotation_rest_required_fields(request_type=warehouse.GetAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_annotation") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_annotation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetAnnotationRequest.pb(warehouse.GetAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Annotation.to_json(warehouse.Annotation()) + + request = warehouse.GetAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Annotation() + + client.get_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_annotation(request) + + +def test_get_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}" % client.transport._host, args[1]) + + +def test_get_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_annotation( + warehouse.GetAnnotationRequest(), + name='name_value', + ) + + +def test_get_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListAnnotationsRequest, + dict, +]) +def test_list_annotations_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAnnotationsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAnnotationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_annotations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnnotationsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_annotations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_annotations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_annotations] = mock_rpc + + request = {} + client.list_annotations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_annotations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_annotations_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_annotations") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_annotations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListAnnotationsRequest.pb(warehouse.ListAnnotationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListAnnotationsResponse.to_json(warehouse.ListAnnotationsResponse()) + + request = warehouse.ListAnnotationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListAnnotationsResponse() + + client.list_annotations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_annotations_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListAnnotationsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_annotations(request) + + +def test_list_annotations_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListAnnotationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListAnnotationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_annotations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*/assets/*}/annotations" % client.transport._host, args[1]) + + +def test_list_annotations_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_annotations( + warehouse.ListAnnotationsRequest(), + parent='parent_value', + ) + + +def test_list_annotations_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + warehouse.Annotation(), + ], + next_page_token='abc', + ), + warehouse.ListAnnotationsResponse( + annotations=[], + next_page_token='def', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + ], + next_page_token='ghi', + ), + warehouse.ListAnnotationsResponse( + annotations=[ + warehouse.Annotation(), + warehouse.Annotation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListAnnotationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + + pager = client.list_annotations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.Annotation) + for i in results) + + pages = list(client.list_annotations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateAnnotationRequest, + dict, +]) +def test_update_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'annotation': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'}} + request_init["annotation"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5', 'user_specified_annotation': {'key': 'key_value', 'value': {'int_value': 967, 'float_value': 0.117, 'str_value': 'str_value_value', 'datetime_value': 'datetime_value_value', 'geo_coordinate': {'latitude': 0.86, 'longitude': 0.971}, 'proto_any_value': {'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}, 'bool_value': True, 'customized_struct_data_value': {'fields': {}}}, 'partition': {'temporal_partition': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'spatial_partition': {'x_min': 539, 'y_min': 540, 'x_max': 541, 'y_max': 542}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateAnnotationRequest.meta.fields["annotation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["annotation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["annotation"][field])): + del request_init["annotation"][field][i][subfield] + else: + del request_init["annotation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_annotation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.Annotation) + assert response.name == 'name_value' + +def test_update_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_annotation] = mock_rpc + + request = {} + client.update_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_annotation_rest_required_fields(request_type=warehouse.UpdateAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_annotation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("annotation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_annotation") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_annotation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateAnnotationRequest.pb(warehouse.UpdateAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.Annotation.to_json(warehouse.Annotation()) + + request = warehouse.UpdateAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.Annotation() + + client.update_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'annotation': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_annotation(request) + + +def test_update_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.Annotation() + + # get arguments that satisfy an http rule for this method + sample_request = {'annotation': {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{annotation.name=projects/*/locations/*/corpora/*/assets/*/annotations/*}" % client.transport._host, args[1]) + + +def test_update_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_annotation( + warehouse.UpdateAnnotationRequest(), + annotation=warehouse.Annotation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteAnnotationRequest, + dict, +]) +def test_delete_annotation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_annotation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_annotation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_annotation] = mock_rpc + + request = {} + client.delete_annotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_annotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_annotation_rest_required_fields(request_type=warehouse.DeleteAnnotationRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_annotation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_annotation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_annotation_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_annotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_annotation_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_annotation") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteAnnotationRequest.pb(warehouse.DeleteAnnotationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteAnnotationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_annotation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_annotation_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteAnnotationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_annotation(request) + + +def test_delete_annotation_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4/annotations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_annotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/assets/*/annotations/*}" % client.transport._host, args[1]) + + +def test_delete_annotation_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_annotation( + warehouse.DeleteAnnotationRequest(), + name='name_value', + ) + + +def test_delete_annotation_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_ingest_asset_rest_no_http_options(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = warehouse.IngestAssetRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.ingest_asset(requests) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ClipAssetRequest, + dict, +]) +def test_clip_asset_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ClipAssetResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ClipAssetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.clip_asset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.ClipAssetResponse) + +def test_clip_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clip_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clip_asset] = mock_rpc + + request = {} + client.clip_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.clip_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_clip_asset_rest_required_fields(request_type=warehouse.ClipAssetRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clip_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clip_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ClipAssetResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ClipAssetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.clip_asset(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_clip_asset_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.clip_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "temporalPartition", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_clip_asset_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_clip_asset") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_clip_asset") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ClipAssetRequest.pb(warehouse.ClipAssetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ClipAssetResponse.to_json(warehouse.ClipAssetResponse()) + + request = warehouse.ClipAssetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ClipAssetResponse() + + client.clip_asset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_clip_asset_rest_bad_request(transport: str = 'rest', request_type=warehouse.ClipAssetRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.clip_asset(request) + + +def test_clip_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GenerateHlsUriRequest, + dict, +]) +def test_generate_hls_uri_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.GenerateHlsUriResponse( + uri='uri_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.GenerateHlsUriResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_hls_uri(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.GenerateHlsUriResponse) + assert response.uri == 'uri_value' + +def test_generate_hls_uri_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_hls_uri in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_hls_uri] = mock_rpc + + request = {} + client.generate_hls_uri(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_hls_uri(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_hls_uri_rest_required_fields(request_type=warehouse.GenerateHlsUriRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_hls_uri._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_hls_uri._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.GenerateHlsUriResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.GenerateHlsUriResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.generate_hls_uri(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_hls_uri_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_hls_uri._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "temporalPartitions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_hls_uri_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_generate_hls_uri") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_generate_hls_uri") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GenerateHlsUriRequest.pb(warehouse.GenerateHlsUriRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.GenerateHlsUriResponse.to_json(warehouse.GenerateHlsUriResponse()) + + request = warehouse.GenerateHlsUriRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.GenerateHlsUriResponse() + + client.generate_hls_uri(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_hls_uri_rest_bad_request(transport: str = 'rest', request_type=warehouse.GenerateHlsUriRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/assets/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_hls_uri(request) + + +def test_generate_hls_uri_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.CreateSearchConfigRequest, + dict, +]) +def test_create_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request_init["search_config"] = {'name': 'name_value', 'facet_property': {'fixed_range_bucket_spec': {'bucket_start': {'string_value': 'string_value_value', 'integer_value': 1386, 'datetime_value': {'year': 433, 'month': 550, 'day': 318, 'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543, 'utc_offset': {'seconds': 751, 'nanos': 543}, 'time_zone': {'id': 'id_value', 'version': 'version_value'}}}, 'bucket_granularity': {}, 'bucket_count': 1286}, 'custom_range_bucket_spec': {'endpoints': {}}, 'datetime_bucket_spec': {'granularity': 1}, 'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2'], 'display_name': 'display_name_value', 'result_size': 1209, 'bucket_type': 1}, 'search_criteria_property': {'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2']}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.CreateSearchConfigRequest.meta.fields["search_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_config"][field])): + del request_init["search_config"][field][i][subfield] + else: + del request_init["search_config"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_search_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + +def test_create_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_config] = mock_rpc + + request = {} + client.create_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_search_config_rest_required_fields(request_type=warehouse.CreateSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["search_config_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "searchConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "searchConfigId" in jsonified_request + assert jsonified_request["searchConfigId"] == request_init["search_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["searchConfigId"] = 'search_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("search_config_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "searchConfigId" in jsonified_request + assert jsonified_request["searchConfigId"] == 'search_config_id_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_search_config(request) + + expected_params = [ + ( + "searchConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("searchConfigId", )) & set(("parent", "searchConfig", "searchConfigId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_create_search_config") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_create_search_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.CreateSearchConfigRequest.pb(warehouse.CreateSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchConfig.to_json(warehouse.SearchConfig()) + + request = warehouse.CreateSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchConfig() + + client.create_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.CreateSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_search_config(request) + + +def test_create_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*}/searchConfigs" % client.transport._host, args[1]) + + +def test_create_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_search_config( + warehouse.CreateSearchConfigRequest(), + parent='parent_value', + search_config=warehouse.SearchConfig(name='name_value'), + search_config_id='search_config_id_value', + ) + + +def test_create_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.UpdateSearchConfigRequest, + dict, +]) +def test_update_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'search_config': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'}} + request_init["search_config"] = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4', 'facet_property': {'fixed_range_bucket_spec': {'bucket_start': {'string_value': 'string_value_value', 'integer_value': 1386, 'datetime_value': {'year': 433, 'month': 550, 'day': 318, 'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543, 'utc_offset': {'seconds': 751, 'nanos': 543}, 'time_zone': {'id': 'id_value', 'version': 'version_value'}}}, 'bucket_granularity': {}, 'bucket_count': 1286}, 'custom_range_bucket_spec': {'endpoints': {}}, 'datetime_bucket_spec': {'granularity': 1}, 'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2'], 'display_name': 'display_name_value', 'result_size': 1209, 'bucket_type': 1}, 'search_criteria_property': {'mapped_fields': ['mapped_fields_value1', 'mapped_fields_value2']}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = warehouse.UpdateSearchConfigRequest.meta.fields["search_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_config"][field])): + del request_init["search_config"][field][i][subfield] + else: + del request_init["search_config"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_search_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + +def test_update_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_config] = mock_rpc + + request = {} + client.update_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_search_config_rest_required_fields(request_type=warehouse.UpdateSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_search_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("searchConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_update_search_config") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_update_search_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.UpdateSearchConfigRequest.pb(warehouse.UpdateSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchConfig.to_json(warehouse.SearchConfig()) + + request = warehouse.UpdateSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchConfig() + + client.update_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.UpdateSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'search_config': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_search_config(request) + + +def test_update_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'search_config': {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{search_config.name=projects/*/locations/*/corpora/*/searchConfigs/*}" % client.transport._host, args[1]) + + +def test_update_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_search_config( + warehouse.UpdateSearchConfigRequest(), + search_config=warehouse.SearchConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.GetSearchConfigRequest, + dict, +]) +def test_get_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_search_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, warehouse.SearchConfig) + assert response.name == 'name_value' + +def test_get_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_config] = mock_rpc + + request = {} + client.get_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_search_config_rest_required_fields(request_type=warehouse.GetSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_search_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_get_search_config") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_get_search_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.GetSearchConfigRequest.pb(warehouse.GetSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchConfig.to_json(warehouse.SearchConfig()) + + request = warehouse.GetSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchConfig() + + client.get_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.GetSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_search_config(request) + + +def test_get_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}" % client.transport._host, args[1]) + + +def test_get_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_search_config( + warehouse.GetSearchConfigRequest(), + name='name_value', + ) + + +def test_get_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.DeleteSearchConfigRequest, + dict, +]) +def test_delete_search_config_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_search_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_search_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_config] = mock_rpc + + request = {} + client.delete_search_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_search_config_rest_required_fields(request_type=warehouse.DeleteSearchConfigRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_search_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_search_config_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_search_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_search_config_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_delete_search_config") as pre: + pre.assert_not_called() + pb_message = warehouse.DeleteSearchConfigRequest.pb(warehouse.DeleteSearchConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = warehouse.DeleteSearchConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_search_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_search_config_rest_bad_request(transport: str = 'rest', request_type=warehouse.DeleteSearchConfigRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_search_config(request) + + +def test_delete_search_config_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/corpora/sample3/searchConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_search_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/corpora/*/searchConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_search_config_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_search_config( + warehouse.DeleteSearchConfigRequest(), + name='name_value', + ) + + +def test_delete_search_config_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + warehouse.ListSearchConfigsRequest, + dict, +]) +def test_list_search_configs_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListSearchConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_search_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_search_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_configs] = mock_rpc + + request = {} + client.list_search_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_search_configs_rest_required_fields(request_type=warehouse.ListSearchConfigsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.ListSearchConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_search_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_search_configs_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_search_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_search_configs_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_list_search_configs") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_list_search_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.ListSearchConfigsRequest.pb(warehouse.ListSearchConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.ListSearchConfigsResponse.to_json(warehouse.ListSearchConfigsResponse()) + + request = warehouse.ListSearchConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.ListSearchConfigsResponse() + + client.list_search_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_search_configs_rest_bad_request(transport: str = 'rest', request_type=warehouse.ListSearchConfigsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_search_configs(request) + + +def test_list_search_configs_rest_flattened(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.ListSearchConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.ListSearchConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_search_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*/corpora/*}/searchConfigs" % client.transport._host, args[1]) + + +def test_list_search_configs_rest_flattened_error(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_search_configs( + warehouse.ListSearchConfigsRequest(), + parent='parent_value', + ) + + +def test_list_search_configs_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + next_page_token='abc', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[], + next_page_token='def', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + ], + next_page_token='ghi', + ), + warehouse.ListSearchConfigsResponse( + search_configs=[ + warehouse.SearchConfig(), + warehouse.SearchConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.ListSearchConfigsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.list_search_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchConfig) + for i in results) + + pages = list(client.list_search_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + warehouse.SearchAssetsRequest, + dict, +]) +def test_search_assets_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = warehouse.SearchAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAssetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_search_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_assets] = mock_rpc + + request = {} + client.search_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_search_assets_rest_required_fields(request_type=warehouse.SearchAssetsRequest): + transport_class = transports.WarehouseRestTransport + + request_init = {} + request_init["corpus"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["corpus"] = 'corpus_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "corpus" in jsonified_request + assert jsonified_request["corpus"] == 'corpus_value' + + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = warehouse.SearchAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = warehouse.SearchAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_assets_rest_unset_required_fields(): + transport = transports.WarehouseRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("corpus", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_assets_rest_interceptors(null_interceptor): + transport = transports.WarehouseRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WarehouseRestInterceptor(), + ) + client = WarehouseClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WarehouseRestInterceptor, "post_search_assets") as post, \ + mock.patch.object(transports.WarehouseRestInterceptor, "pre_search_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = warehouse.SearchAssetsRequest.pb(warehouse.SearchAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = warehouse.SearchAssetsResponse.to_json(warehouse.SearchAssetsResponse()) + + request = warehouse.SearchAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = warehouse.SearchAssetsResponse() + + client.search_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_assets_rest_bad_request(transport: str = 'rest', request_type=warehouse.SearchAssetsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'corpus': 'projects/sample1/locations/sample2/corpora/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_assets(request) + + +def test_search_assets_rest_pager(transport: str = 'rest'): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + next_page_token='abc', + ), + warehouse.SearchAssetsResponse( + search_result_items=[], + next_page_token='def', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + ], + next_page_token='ghi', + ), + warehouse.SearchAssetsResponse( + search_result_items=[ + warehouse.SearchResultItem(), + warehouse.SearchResultItem(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(warehouse.SearchAssetsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'corpus': 'projects/sample1/locations/sample2/corpora/sample3'} + + pager = client.search_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, warehouse.SearchResultItem) + for i in results) + + pages = list(client.search_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_ingest_asset_rest_error(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.ingest_asset({}) + assert ( + "Method IngestAsset is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WarehouseClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WarehouseClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WarehouseClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WarehouseClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WarehouseClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WarehouseGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WarehouseGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WarehouseGrpcTransport, + transports.WarehouseGrpcAsyncIOTransport, + transports.WarehouseRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = WarehouseClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WarehouseGrpcTransport, + ) + +def test_warehouse_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WarehouseTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_warehouse_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.visionai_v1alpha1.services.warehouse.transports.WarehouseTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WarehouseTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_asset', + 'update_asset', + 'get_asset', + 'list_assets', + 'delete_asset', + 'create_corpus', + 'get_corpus', + 'update_corpus', + 'list_corpora', + 'delete_corpus', + 'create_data_schema', + 'update_data_schema', + 'get_data_schema', + 'delete_data_schema', + 'list_data_schemas', + 'create_annotation', + 'get_annotation', + 'list_annotations', + 'update_annotation', + 'delete_annotation', + 'ingest_asset', + 'clip_asset', + 'generate_hls_uri', + 'create_search_config', + 'update_search_config', + 'get_search_config', + 'delete_search_config', + 'list_search_configs', + 'search_assets', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_warehouse_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.visionai_v1alpha1.services.warehouse.transports.WarehouseTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WarehouseTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_warehouse_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.visionai_v1alpha1.services.warehouse.transports.WarehouseTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WarehouseTransport() + adc.assert_called_once() + + +def test_warehouse_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) + WarehouseClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WarehouseGrpcTransport, + transports.WarehouseGrpcAsyncIOTransport, + ], +) +def test_warehouse_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WarehouseGrpcTransport, + transports.WarehouseGrpcAsyncIOTransport, + transports.WarehouseRestTransport, + ], +) +def test_warehouse_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WarehouseGrpcTransport, grpc_helpers), + (transports.WarehouseGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_warehouse_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( + "visionai.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="visionai.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WarehouseGrpcTransport, transports.WarehouseGrpcAsyncIOTransport]) +def test_warehouse_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_warehouse_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.WarehouseRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_warehouse_rest_lro_client(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_warehouse_host_no_port(transport_name): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_warehouse_host_with_port(transport_name): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='visionai.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'visionai.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://visionai.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_warehouse_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WarehouseClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WarehouseClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_asset._session + session2 = client2.transport.create_asset._session + assert session1 != session2 + session1 = client1.transport.update_asset._session + session2 = client2.transport.update_asset._session + assert session1 != session2 + session1 = client1.transport.get_asset._session + session2 = client2.transport.get_asset._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.delete_asset._session + session2 = client2.transport.delete_asset._session + assert session1 != session2 + session1 = client1.transport.create_corpus._session + session2 = client2.transport.create_corpus._session + assert session1 != session2 + session1 = client1.transport.get_corpus._session + session2 = client2.transport.get_corpus._session + assert session1 != session2 + session1 = client1.transport.update_corpus._session + session2 = client2.transport.update_corpus._session + assert session1 != session2 + session1 = client1.transport.list_corpora._session + session2 = client2.transport.list_corpora._session + assert session1 != session2 + session1 = client1.transport.delete_corpus._session + session2 = client2.transport.delete_corpus._session + assert session1 != session2 + session1 = client1.transport.create_data_schema._session + session2 = client2.transport.create_data_schema._session + assert session1 != session2 + session1 = client1.transport.update_data_schema._session + session2 = client2.transport.update_data_schema._session + assert session1 != session2 + session1 = client1.transport.get_data_schema._session + session2 = client2.transport.get_data_schema._session + assert session1 != session2 + session1 = client1.transport.delete_data_schema._session + session2 = client2.transport.delete_data_schema._session + assert session1 != session2 + session1 = client1.transport.list_data_schemas._session + session2 = client2.transport.list_data_schemas._session + assert session1 != session2 + session1 = client1.transport.create_annotation._session + session2 = client2.transport.create_annotation._session + assert session1 != session2 + session1 = client1.transport.get_annotation._session + session2 = client2.transport.get_annotation._session + assert session1 != session2 + session1 = client1.transport.list_annotations._session + session2 = client2.transport.list_annotations._session + assert session1 != session2 + session1 = client1.transport.update_annotation._session + session2 = client2.transport.update_annotation._session + assert session1 != session2 + session1 = client1.transport.delete_annotation._session + session2 = client2.transport.delete_annotation._session + assert session1 != session2 + session1 = client1.transport.ingest_asset._session + session2 = client2.transport.ingest_asset._session + assert session1 != session2 + session1 = client1.transport.clip_asset._session + session2 = client2.transport.clip_asset._session + assert session1 != session2 + session1 = client1.transport.generate_hls_uri._session + session2 = client2.transport.generate_hls_uri._session + assert session1 != session2 + session1 = client1.transport.create_search_config._session + session2 = client2.transport.create_search_config._session + assert session1 != session2 + session1 = client1.transport.update_search_config._session + session2 = client2.transport.update_search_config._session + assert session1 != session2 + session1 = client1.transport.get_search_config._session + session2 = client2.transport.get_search_config._session + assert session1 != session2 + session1 = client1.transport.delete_search_config._session + session2 = client2.transport.delete_search_config._session + assert session1 != session2 + session1 = client1.transport.list_search_configs._session + session2 = client2.transport.list_search_configs._session + assert session1 != session2 + session1 = client1.transport.search_assets._session + session2 = client2.transport.search_assets._session + assert session1 != session2 +def test_warehouse_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WarehouseGrpcTransport( + 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_warehouse_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WarehouseGrpcAsyncIOTransport( + 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.WarehouseGrpcTransport, transports.WarehouseGrpcAsyncIOTransport]) +def test_warehouse_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.WarehouseGrpcTransport, transports.WarehouseGrpcAsyncIOTransport]) +def test_warehouse_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_warehouse_grpc_lro_client(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_warehouse_grpc_lro_async_client(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_annotation_path(): + project_number = "squid" + location = "clam" + corpus = "whelk" + asset = "octopus" + annotation = "oyster" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}/annotations/{annotation}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, annotation=annotation, ) + actual = WarehouseClient.annotation_path(project_number, location, corpus, asset, annotation) + assert expected == actual + + +def test_parse_annotation_path(): + expected = { + "project_number": "nudibranch", + "location": "cuttlefish", + "corpus": "mussel", + "asset": "winkle", + "annotation": "nautilus", + } + path = WarehouseClient.annotation_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_annotation_path(path) + assert expected == actual + +def test_asset_path(): + project_number = "scallop" + location = "abalone" + corpus = "squid" + asset = "clam" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/assets/{asset}".format(project_number=project_number, location=location, corpus=corpus, asset=asset, ) + actual = WarehouseClient.asset_path(project_number, location, corpus, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "project_number": "whelk", + "location": "octopus", + "corpus": "oyster", + "asset": "nudibranch", + } + path = WarehouseClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_asset_path(path) + assert expected == actual + +def test_corpus_path(): + project_number = "cuttlefish" + location = "mussel" + corpus = "winkle" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}".format(project_number=project_number, location=location, corpus=corpus, ) + actual = WarehouseClient.corpus_path(project_number, location, corpus) + assert expected == actual + + +def test_parse_corpus_path(): + expected = { + "project_number": "nautilus", + "location": "scallop", + "corpus": "abalone", + } + path = WarehouseClient.corpus_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_corpus_path(path) + assert expected == actual + +def test_data_schema_path(): + project_number = "squid" + location = "clam" + corpus = "whelk" + data_schema = "octopus" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}".format(project_number=project_number, location=location, corpus=corpus, data_schema=data_schema, ) + actual = WarehouseClient.data_schema_path(project_number, location, corpus, data_schema) + assert expected == actual + + +def test_parse_data_schema_path(): + expected = { + "project_number": "oyster", + "location": "nudibranch", + "corpus": "cuttlefish", + "data_schema": "mussel", + } + path = WarehouseClient.data_schema_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_data_schema_path(path) + assert expected == actual + +def test_search_config_path(): + project_number = "winkle" + location = "nautilus" + corpus = "scallop" + search_config = "abalone" + expected = "projects/{project_number}/locations/{location}/corpora/{corpus}/searchConfigs/{search_config}".format(project_number=project_number, location=location, corpus=corpus, search_config=search_config, ) + actual = WarehouseClient.search_config_path(project_number, location, corpus, search_config) + assert expected == actual + + +def test_parse_search_config_path(): + expected = { + "project_number": "squid", + "location": "clam", + "corpus": "whelk", + "search_config": "octopus", + } + path = WarehouseClient.search_config_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_search_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WarehouseClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = WarehouseClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = WarehouseClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = WarehouseClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WarehouseClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = WarehouseClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = WarehouseClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = WarehouseClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = WarehouseClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = WarehouseClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WarehouseClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.WarehouseTransport, '_prep_wrapped_messages') as prep: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WarehouseTransport, '_prep_wrapped_messages') as prep: + transport_class = WarehouseClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/clusters/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = WarehouseAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = WarehouseClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (WarehouseClient, transports.WarehouseGrpcTransport), + (WarehouseAsyncClient, transports.WarehouseGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )